【问题标题】:Android: setText onItemClick NPEAndroid:setText onItemClick NPE
【发布时间】:2012-06-19 20:20:09
【问题描述】:

我不明白为什么在设置文本视图字符串时会收到 NPE。我全部都使用了这些,但为什么在这个 onItemClick() 方法上使用 NPE??

感谢您的帮助。

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        . . .
        TextView title = (TextView) view.findViewById(R.id.navigationTitle);
        String navTitle = ((TextView) view.findViewById(R.id.listLabel)).getText().toString();
        title.setText(navTitle);//<--NPE AT THIS LINE - NO OTHER INFO FROM LOGCAT THAT IS FROM MY CLASSES!!
        . . . 
}

【问题讨论】:

    标签: android nullpointerexception settext onitemclick


    【解决方案1】:

    99% 'title' 对象为空,因为它不存在于 onItemClick 方法传入的 'view' 对象中。

    尝试将 view.findViewById 更改为仅 findViewById,假设 textview R.id.navigationTitle 存在于 Activity 中。

    【讨论】:

    【解决方案2】:

    TextView title 为 null,因此如果 navigationTitle 在您的主 Activity 布局中,请尝试此操作:

     TextView title = (TextView)findViewById(R.id.navigationTitle);
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            . . .
            String navTitle = ((TextView) view.findViewById(R.id.listLabel)).getText().toString();
            title.setText(navTitle);
            . . . 
    }
    

    【讨论】:

    【解决方案3】:

    感谢@imran khan 和@azgolfer 让我思考:

    我变了:

    TextView title = (TextView) view.findViewById(R.id.navigationTitle);
    

    到:

    TextView title = (TextView) getActivity().findViewById(R.id.navigationTitle);
    

    现在它不为空了!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 2013-09-09
      • 2014-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多