textView setText() NullPointerException

前端 未结 3 1401
伪装坚强ぢ
伪装坚强ぢ 2021-01-22 12:13

I have an almost completely Vanilla App. All I\'m trying to do is change the text of a textView, but it gives me a NullPointerException. I have no XML configuration, no added me

3条回答
  •  粉色の甜心
    2021-01-22 12:47

    The TextView textView1 you are trying to refer is in the Fragment's inflated layout. The content view you have set in the Activity is activity_main.xml, which probably doesn't have the textView1 component.

    The solution is to override the Fragment's onViewCreated() method and set the text there

    @Override
    public void onViewCreated (View view, Bundle savedInstanceState)
    {
        TextView tv = (TextView) view.findViewById(R.id.textView1);
        tv.setText("My text");
        /* Other code here */
    }
    

    Remember to call view.findViewById(R.id.textView1) and not just findViewById(R.id.textView1) because in the latter, you are trying to access the enclosing class non-static method in a static inner class. By calling view.findViewById(R.id.textView1) you are calling a method of a local variable in the static inner class.

提交回复
热议问题