Android片段和null对象引用

Alw*_*sed 7 java android android-fragments

我试图让我的片段工作,我无法完成任何我想做的事情.

我得到的错误是:

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.TextView.setText(java.lang.CharSequence)'

这是代码:

public class FragmentOne extends Fragment {

    private TextView one;

    public FragmentOne() {
        // Required empty public constructor
    }

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

        one = (TextView) getActivity().findViewById(R.id.one);

        // Displaying the user details on the screen
        one.setText("kjhbguhjg");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment1, container, false);

    }
}
Run Code Online (Sandbox Code Playgroud)

不知道为什么它不起作用.我正在测试这个类只是为了查看文本是否会在textview上更改.我正在使用正确的id,因为我检查了10次,但我认为问题是因为textview one是一个null对象.但为什么它没有找到id?

Dan*_*son 13

onCreate()之前调用onCreateView(),因此您将无法访问它onCreate().

解决方案: 移动

one = (TextView) getActivity().findViewById(R.id.one);
Run Code Online (Sandbox Code Playgroud)

onViewCreated()代替.

有关片段生命周期的概述,请参见下图.

新的代码片段如下所示:

public class FragmentOne extends Fragment {


    private TextView one;

    public FragmentOne() {
        // Required empty public constructor
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment1, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
        one = (TextView) getActivity().findViewById(R.id.one);
        // Displaying the user details on the screen
        one.setText("kjhbguhjg");
    }
}
Run Code Online (Sandbox Code Playgroud)

片段生命周期