【问题标题】:How to pass arguments to a Fragment which is currently active?如何将参数传递给当前处于活动状态的片段?
【发布时间】:2017-11-23 19:40:56
【问题描述】:

我有一个活动,它根据按钮点击实例化 4 个不同的片段。 我必须将附加值传递给当前处于活动状态的片段。

最初,当我通过 setArguments 传递值时,正在传递值。但是第二次没有将值传递给 Fragment。

我尝试记录并在 onCreate 和 onCreateView 方法中放置断点,但这些方法根本没有被第二次调用。

这是我的代码

活动中的代码

Bundle bundle = new Bundle();
bundle.putInt("from", "1");
bundle.putString("label","One");

MyFragment1 myFragment1 = new MyFragment1();
myFragment1.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.fragment1, myFragment1)
.commitAllowingStateLoss();

片段中的代码

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    Bundle b = getArguments();
    if(b!=null)
    { 

    }


}

【问题讨论】:

  • public void onCreate(@Nullable Bundle savedInstanceState) { 尝试进入 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  • 你可以在这里找到类似问题的解决方案:stackoverflow.com/questions/41454596/…

标签: android android-fragments


【解决方案1】:

来自活动

Bundle bundle = new Bundle();
bundle.putInt("from", "1");
bundle.putString("label","One");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

在 Fragment 的 onCreateView 方法中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String label = getArguments().getString("label");    
    int i=getArguments().getInt("from"); 
    return inflater.inflate(R.layout.fragment, container, false);
}

【讨论】:

    【解决方案2】:

    找到解决办法

    我在Activity的onCreate中给出了这行代码。

    MyFragment1 myFragment1 = new MyFragment1();
    

    在将其传递给片段之前,我必须恢复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      相关资源
      最近更新 更多