【问题标题】:Setting arguments to fragment causes IllegalStateException为片段设置参数会导致 IllegalStateException
【发布时间】:2013-12-19 18:03:40
【问题描述】:

我正在使用以下代码为从 XML 膨胀的片段设置参数:

  fragment_phone=(AddNewFragment)fm.findFragmentById(R.I'd.phone_fragment);
   Bundle args=fragment_phone.getArguments();
    if(args==null)
    {
        args=new Bundle();
        args.putString("hint","Phone");
        fragment_phone.set arguments(args);
      }
      else
            args.putString("hint","Phone");

   //Similarly for two other fragments that are also instances of AddNewFragment

我使用三个Bundle 对象,每个片段一个。 Logcat 说Fragment is already active java.lang.IllegalStateException at android.support.v4.app.setArguments

我尝试删除setArguments,当我调用它时会导致NullPointerException

    Bundle args=get arguments();
    String hint=args.getString("hint");
    Log.d(TAG," Hint :"+hint);

【问题讨论】:

  • 您不能为 xml 布局中定义的片段设置参数。
  • 那我怎么给他们传递任何值,我可以在 XML 中定义时这样做
  • 不在 xml 中。您可以手动添加它们并使用带有 setArguments() 的 Bundles,或者您可以在它们上调用 setter 方法(但您需要自己保存数据,因为它不会像参数一样自动保存)。

标签: android android-fragments nullpointerexception illegalstateexception


【解决方案1】:

使用 Fragments,您始终必须实现 interface

  1. 在fragment中创建interface,用于与其他fragment通信。

  2. 在您的MainActivityActivity 类中实现interface

  3. onActivityCreated() 中调用getArguments 以避免任何NullPointerExceptions

更多信息请参见this

【讨论】:

  • 我想在接口回调中使用片段的资源ID,这样我就可以正确获取每个实例的值...有没有办法从FragmentManager或其他地方获取资源ID。
猜你喜欢
  • 2018-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多