Passing parameters from Android FragmentActivity to Fragment

白昼怎懂夜的黑 提交于 2019-12-01 06:44:01
  1. Get rid of Activity from the names of all classes that do not inherit from Activity. For example, IndexFragmentActivity is not an Activity.

  2. In onCreate() of your actual activity, you are calling findFragmentById() to retrieve a fragment, then calling newInstance() on that fragment. However, the fragment will not exist the first time onCreate() is called, and you will fail here with a NullPointerException. Please correctly handle this case.

  3. The method name newInstance in Java is most commonly associated with the factory pattern, where newInstance() is a static method used in place of a public constructor to create instances of some class. Your newInstance() method is not static. This will cause confusion for those who come after you to maintain the code.

  4. You call newInstance() in onCreate(), create the new fragment instance, and then throw it away, which is a waste of time.

Hence, assuming that your original instance of your fragment (wherever it came from) does not have an arguments Bundle set, that would explain your NullPointerException in getSelectedIndex().

When Im trying to pass a parameter from FragmentActivity to a Fragment

To pass a parameter to a newly created fragment, using a static newInstance() method and the arguments Bundle to create the new fragment is perfectly reasonable.

To pass a parameter to a fragment that already exists, simply call some setter method on that fragment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!