【问题标题】:NullPointerException on OnclickListner of a button in the alertDialogue在 alertDialogue 中的按钮的 OnclickListner 上出现 NullPointerException
【发布时间】:2012-10-03 18:14:46
【问题描述】:

我在 alertbuilder 中添加的布局有两个按钮。但我无法为此设置 onClickListner。这个异常正在发生。请看我的代码。 自定义 alertDialogue 的 XML。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_common"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<EditText
    android:id="@+id/user_text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="7dp"
    android:singleLine="true" >

    <requestFocus />
</EditText>

 <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Search" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Cancel" />
</LinearLayout>

AlertDialog.Builder alert = new AlertDialog.Builder(Myclass.this);
    alert.setTitle("title");
    alert.setIcon(iconImage);
    LayoutInflater inflater =    (LayoutInflater)MyClass.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.search_dialogue, null, false);
    user_input= (EditText)view.findViewById(R.id.user_text);
    Button cancel = (Button) findViewById(R.id.cancel);
    cancel.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });

    if(content.equals("")) {
        user_input.setHint(hint);
    } else {
        user_input.setText(content);
    }
    alert.setView(view);
    searchAlert = alert.create();
    searchAlert.show();

【问题讨论】:

    标签: android android-alertdialog onclicklistener


    【解决方案1】:

    您在findViewById 之前缺少view,排除view 您指的是活动..:

    Button cancel = (Button) view.findViewById(R.id.cancel);
    

    【讨论】:

      【解决方案2】:
      Button cancel = (Button) view.findViewById(R.id.cancel);
      

      【讨论】:

      • 您正在尝试从活动中膨胀,您需要视图才能从对话框视图中膨胀。
      【解决方案3】:

      在这里查看

      user_input= (EditText)view.findViewById(R.id.user_text);//defined view for user_input
      Button cancel = (Button) findViewById(R.id.cancel);//not defined view for button
      

      改成

      Button cancel = (Button)view. findViewById(R.id.cancel);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多