片段投掷Nullpointer

时间:2017-07-11 17:20:28

标签: java android android-fragments nullpointerexception

因此我在TextView内操纵Fragment时遇到问题。 我有一个简单的回调界面,只定义onCallBackReceived(),当我的方法onCallbackReceived()被回调时,我想更改TextView的文字,但方法setText("onCallback")抛出NullPointerException 。 Exception表示该方法是在null对象引用上调用的,但我首先使用findViewById()初始化它。请帮忙。

public class MyFragment extends Fragment implements MySimpleCallback {

     TextView textView;

     @Nullable
     @Override
     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
         return inflater.inflate(R.layout.panel_fragment, container, false);
     }

     @Override
     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
         textView = (TextView) view.findViewById(R.id.text_view);
         textView.setText("Okay!");
     }

     @Override
     public void onCallbackReceived() {
         textView.setText("onCallback");
     }

}

1 个答案:

答案 0 :(得分:-1)

也许你可以在onCreateView

中找到TheViewById
public class MyFragment extends Fragment implements MySimpleCallback {

     TextView textView;

     @Nullable
     @Override
     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
         View view = inflater.inflate(R.layout.panel_fragment, container, false);
         textView = (TextView) view.findViewById(R.id.text_view);
         return view;
     }

     @Override
     public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
         textView.setText("Okay!");
     }

     @Override
     public void onCallbackReceived() {
         textView.setText("onCallback");
     }
}