繁体   English   中英

如何在不影响片段可重用性的情况下从片段开始活动

[英]how to get from a fragment to an activity without disturbing fragment's reausability

现在,这困扰了我很多。

我想从一个片段开始一项活动,而又不影响该片段的可重用性。 这意味着我无法直接从片段内部开始将Intent启动到该片段当前附加的活动。

这是有疑问的代码

//This is the code inside the fragment 

public void onStart() {
    super.onStart();
    View view = getView();

    switch (position){
        //case 1 is the case when the user clicks the ADD List Item from a ListFragment. 
        //Position is the position of ADD in the List Fragment.
        case 1:{
            Intent intent = new Intent(/*what exactly should I put here?*/  ,  
        /*this is where the reference to activity the fragment is attached to goes.
            But we dont know what activty the fragment is attached to, as it is reusable 
         and may get attached to different activity at different times*/);
        }

        case 2:{
            //this is the case when user decides to view the entered text in the array list.
            TextView textView = (TextView)view.findViewById(R.id.display_name);
            int size = workout.arrayList.size();
            Object[] array = workout.arrayList.toArray();
            for(int i=0;i<array.length;i++){
                textView.setText((String)array[i] + "\n");
            }
        }
    }

}

我觉得数据可能不足,尽管我不确定还可以提供什么,对此感到抱歉。

如果需要更多数据,请告诉我。

在片段内部,我们使用以下方法获取意图的上下文:

Intent intent = new Intent(getActivity(),AnyActivity.class);

要么

Intent intent = new Intent(getView.getContext(),AnyActivity.class);

AnyActivity()可以是任何活动,包括当前具有Fragment

您可以像这样打开相同的活动。

        Intent intent = new Intent(getActivity(),SameActivity.class);

      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

更新要在不同的值上重用该片段,请在事务期间将参数传递给片段...。

      Bundle bundle = new Bundle();
      bundle.put("className", "SameActivity");
      fragment.setArguments(bundle);

在片段中从包中获取类名...不同的类将作为包传递不同的参数。

OtherActivity中,束看起来像这样。

      Bundle bundle = new Bundle();
      bundle.put("className", "OtherActivity");
      fragment.setArguments(bundle);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM