简体   繁体   English

对话框按钮单击时,Android应用程序崩溃

[英]Android Application crash on dialog Button click

Im trying to make a Dialog close when button is pressed.But Every time i press the button the application crashes. 我试图在按下按钮时关闭对话框。但是每次我按下按钮时,应用程序都会崩溃。

public class CanvasPaint extends Activity implements OnClickListener {
    final Button widthbtn = (Button) findViewById(R.id.widthbtn);
    final  Button widthpopBtn = (Button) findViewById(R.id.widthpopBtn);

    final Context context = this;

    final Dialog widthDialog = new Dialog(context);

    widthbtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

                widthpopBtn.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        widthDialog.dismiss();
                    }
                });
                widthDialog.show();
        }
    });
}

That's some inception code. 那是一些初始代码。 Why are you setting a click listener inside a click listener? 为什么要在点击监听器中设置点击监听器? It should be more like 应该更像

widthbtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            widthDialog.show();
    }
});

widthpopBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            widthDialog.dismiss();
    }
});

Your dialog layout is not properly inflated, and therefore, your widthpopBtn will be null. 您的对话框布局正确膨胀,因此您的widthpopBtn将为null。 Try inflating the layout like this: 尝试像这样扩大布局:

LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.your_dialog_layout, null);
Button widthpopBtn = (Button) dialogView.findViewById(R.id.widthpopBtn);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM