找出添加了 activity 个片段
Find out in which activity fragment was added
所以基本上我在两个不同的活动中使用相同类型的片段,并且我想在片段中创建和初始化一些变量,前提是它是从特定 activity 添加的。我的问题是如何以编程方式找出 activity 片段被添加到其中。
主要有两种实现方式:
较少模块化的方法,您只需使用 instanceof
进行检查
if(getActivity() instanceof MyActivity)
以及更模块化的方法,您在将片段添加到交易时将一些参数传递给片段:
// this during the transaction to pass extra parameters to the fragment
Fragment f = new MyFragment();
Bundle b = new Bundle();
b.putBoolean("doExtraCode", true);
f.setArguments(b);
然后在片段内:
// check if should execute extras
Bundle b = getArguments();
boolean doExtraCode = b == null? false: b.getBoolean("doExtraCode", false);
所以基本上我在两个不同的活动中使用相同类型的片段,并且我想在片段中创建和初始化一些变量,前提是它是从特定 activity 添加的。我的问题是如何以编程方式找出 activity 片段被添加到其中。
主要有两种实现方式:
较少模块化的方法,您只需使用 instanceof
if(getActivity() instanceof MyActivity)
以及更模块化的方法,您在将片段添加到交易时将一些参数传递给片段:
// this during the transaction to pass extra parameters to the fragment
Fragment f = new MyFragment();
Bundle b = new Bundle();
b.putBoolean("doExtraCode", true);
f.setArguments(b);
然后在片段内:
// check if should execute extras
Bundle b = getArguments();
boolean doExtraCode = b == null? false: b.getBoolean("doExtraCode", false);