【问题标题】:Fragment throwing Nullpointer片段抛出 Nullpointer
【发布时间】:2017-07-11 17:20:28
【问题描述】:

所以我在Fragment 中操作我的TextView 时遇到问题。 我有简单的回调接口,只定义onCallBackReceived(),当我的方法onCallbackReceived()被回调时,我想更改我的TextView的文本,但是方法setText("onCallback")抛出NullPointerException。异常说该方法是在空对象引用上调用的,但我首先使用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");
     }

}

【问题讨论】:

  • 你能描述一下你是如何调用onCallbackReceived()方法的吗?
  • MySimpleCallback mySimpleCallback; 然后在创建mySimpleCallback = new MyFargment(); 并通过public void call( MySimpleCallback mySimpleCallback) { mySimleCallback.onCallbackReceived(); } 调用
  • textView.setText("okay") 工作正常吗?
  • 是的,这很令人惊讶;D
  • 你能添加整个代码吗?比如你在哪里实例化你的片段、活动等?

标签: java android android-fragments nullpointerexception


【解决方案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");
     }
}

【讨论】:

  • 还是同样的问题 ;(
猜你喜欢
  • 2015-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-08
  • 1970-01-01
相关资源
最近更新 更多