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

问题描述 投票:-1回答:2

现在这让我烦恼不已。

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

}

我觉得数据可能不够,虽然我不知道还有什么可以提供,对不起。

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

java android android-activity fragment
2个回答
1
投票

在Fragment中,我们使用以下方法获取Intent的Context:

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

要么

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

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


1
投票

你可以打开像这样的活动..

        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);

在fragment中从bundle获取类名...不同的类将不同的参数作为bundle传递给..

在OtherActivity捆绑包看起来像这样..

      Bundle bundle = new Bundle();
      bundle.put("className", "OtherActivity");
      fragment.setArguments(bundle);
© www.soinside.com 2019 - 2024. All rights reserved.