Null TextView object in a fragment

落花浮王杯 提交于 2019-12-02 12:35:44

The problem is your fragment's setNameText() method is called before onCreateView() has run, so your TextView has not been initialized yet. You have to wait until later to set the name text.

If you always have the name text when you are creating and adding the fragment, then it's better to pass that as an argument to the fragment and have it set the text of the TextView at the appropriate time. Something like this:

public class ChallengeFragment extends Fragment {

    public static ChallengeFragment newInstance(String name) {
        ChallengeFragment fragment = new ChallengeFragment();
        Bundle args = new Bundle();
        args.putString("username", name);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Bundle args = getArguments();
        if (args != null) {
            String name = args.getString("username");
            nameText.setText(name);
        }
    }

    // everything else
}

A few things to note:

  1. Do not create a constructor. Fragments need to have a default (no argument) constructor so that Android can instantiate them. This newInstance pattern is typically regarded as the best practice.
  2. Use onActivityCreated because at that time you know the Activity is created and that the fragment's view hierarchy has been created.
  3. Fragment arguments persist across configuration changes, so you shouldn't need to do anything special for that.

Also, you should not be calling onAttach() yourself, that's a lifecycle method that the OS calls on your fragment.

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