在当前片段之前确定片段

时间:2014-11-03 10:48:35

标签: android android-fragments

想象一下,有片段A和片段B. 如果我点击片段A上的按钮,它会导致片段C. 如果我点击片段B上的按钮,它也会导致片段C. 现在我想检测片段C是从哪个片段创建的。有可能吗?

2 个答案:

答案 0 :(得分:2)

你可以简单地设置一个变量并通过bundle将它传递给Fragment C,同时像这样执行FragmentTransaction

Fragment fr=new FragmentA();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
Bundle args = new Bundle();
args.putString("from", "fragmentA");
fr.setArguments(args);
ft.replace(R.id.content_frame, fr);
ft.commit(); 

你可以像这样在片段C中检索它

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    String strtext = getArguments().getString("from"); // with value of strtext,you will get to know from which fragment you come from   
    return inflater.inflate(R.layout.fragment, container, false);
}

答案 1 :(得分:1)

##You can pass a boolean value and toggle between two fragments.##
Bundle args = new Bundle();
args.putBoolean("key",true) // for fragement A
fr.setArguments(args);
ft.replace(R.id.content_frame, fr);
ft.commit(); 
if(getArguments().getBoolean("key");)
Log.e(LOGTAG,"FROM FRAGMENT A");
else
Log.e(LOGTAG,"FROM FRAGMENT B");