0

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

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) { 

              }
            });
4

2 回答 2

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) { 

              }
            });
于 2012-11-21T13:17:48.183 回答
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();
        }
    });
于 2012-11-21T13:16:39.647 回答