在对话框中的按钮上设置单击侦听器时应用程序崩溃...

时间:2012-11-21 13:13:44

标签: android listener

构建一个对话框我想添加一个监听器,但应用程序崩溃。出了什么问题?

private void Info(){

        textview = (TextView) findViewById(R.id.textView1);

        LayoutInflater li = LayoutInflater.from(this);
        View view = li.inflate(R.layout.info, null);

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view).create().show();

        buttonInfo = (Button)findViewById(R.id.buttonInfo);

        buttonInfo.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) { 

              }
            });

2 个答案:

答案 0 :(得分:2)

替换

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

通过

buttonInfo = (Button) findViewById(R.id.buttonInfo);

最终代码

private void Info(){

        textview = (TextView) findViewById(R.id.textView1);

        LayoutInflater li = LayoutInflater.from(this);
        View view = li.inflate(R.layout.info, null);

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view).create().show();

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

        buttonInfo.setOnClickListener(new View.OnClickListener() {
              public void onClick(View view) { 

              }
            });

答案 1 :(得分:1)

我猜这个按钮位于对话框的布局中。

如果是这种情况,请尝试替换

buttonInfo = (Button)findViewById(R.id.buttonInfo);

通过

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

如果你想在以下情况下解雇它,你需要存储创建的AlertDialog(而不是Builder):

    final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).show();

    buttonInfo = (Button) findViewById(R.id.buttonInfo);

    buttonInfo.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            dialog.dismiss();
        }
    });