如何从片段到活动而不会干扰片段的可重用性

时间:2018-02-28 21:00:13

标签: java android android-activity fragment

现在这让我烦恼不已。

我想从片段中获取活动而不会干扰片段的可重用性。这意味着我无法直接从片段中启动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");
            }
        }
    }

}

我觉得数据可能不足,虽然我不确定还能提供什么,对不起。

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

2 个答案:

答案 0 :(得分:1)

在Fragment中,我们使用:

获取Intent的Context
Intent intent = new Intent(getActivity(),AnyActivity.class);

OR

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

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

答案 1 :(得分:1)

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

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

      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

UPDATE 要在不同的值下重用片段,请在事务期间将参数传递给片段...

      Bundle bundle = new Bundle();
      bundle.put("className", "SameActivity");
      fragment.setArguments(bundle);
片段中的

从bundle获取类名...不同的类将不同的参数作为bundle传递。

OtherActivity 包中看起来像这样..

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