0

我设置参数使用以下代码从XML充气片段:设定参数片段导致IllegalStateException异常

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

您无法为在xml布局中定义的片段设置参数。 – Luksprog

+0

那么我怎样才能通过它们的任何值,我可以在XML中定义时做到这一点 – vamsiampolu

+0

不在xml中。您可以手动添加它们并使用带有setArguments()的Bundle,或者您可以调用setter方法(但您需要自己保存数据,因为它不会像使用参数那样自动保存)。 – Luksprog

回答

1

随着你总是要实施interface片段。

  1. 在要与其他片段通信的片段中创建interface

  2. 在您的MainActivityActivity类中执行interface

  3. 拨打getArguments中的onActivityCreated()以避免任何NullPointerExceptions

欲了解更多信息,请参阅this

+0

我想在接口回调中使用片段的资源ID,以便我可以正确地获取每个实例的值......有没有办法从FragmentManager或其他东西获取资源ID。 – vamsiampolu

相关问题