【问题标题】:TextView findviewbyID NullpointerExceptionTextView findviewbyID NullpointerException
【发布时间】:2014-02-13 21:20:27
【问题描述】:

我真的找不到问题...

我有一个 onOptionItemSelected。

调用 textView.setText 时,我得到一个 NPE,因为 findviewbyID 不起作用。有什么想法吗?

AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();

builder.setView(inflater.inflate(R.layout.latest_detailview_info, null))
    .setPositiveButton(R.string.btn_ok,
     new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int id) {
             //do haxx
         }
     });

TextView textView = (TextView) findViewById(R.id.properties_latest_uploadedby);
textView.setText("NPE");

builder.create();
builder.show();

【问题讨论】:

  • findViewById 在您的活动内容中找到一个视图。可能您没有带有 properties_latest_uploadedby id 的 textView。
  • 检查你的活动的 layout.xml 并确保你有一个声明了该 id 的 TextView
  • 我猜测 ID 为 R.id.properties_latest_uploadedby 的 TextView 实际上在您的 R.layout.latest_detailview_info 布局文件中,而不是在您的 Activity 的主布局文件中,对吗?对该 TextView 的 findViewById 调用将在主布局中查找 TextView,但无法找到它,因此返回 null。
  • 你为什么要这样做?

标签: android textview


【解决方案1】:

尝试添加以下更改。

LayoutInflater inflater=this.getLayoutInflater();
View view=inflater.inflate(R.layout.latest_detailview_info, null);

builder.setView(view)
        .setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                //do haxx
            }
        });

TextView textView = (TextView) view.findViewById(R.id.properties_latest_uploadedby);
textView.setText("NPE");

builder.create();
builder.show();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    • 2016-02-13
    相关资源
    最近更新 更多