将侦听器添加到自定义alertdialog内的按钮会导致我的应用程序崩溃

Pha*_*anx 4 android listener android-alertdialog onclicklistener

我在我的应用程序中有一个按钮,允许我打开自定义alertdialog.此警报对话框从XML文件中获取其内容:我在其中有一个按钮(称为filterButton),单选按钮和滑块.以编程方式,还添加了两个按钮(确定,取消).
当我打开对话框警报时,内容会完美显示,但到目前为止还没有创建任何事件.(所以打开alertdialog并显示内容没问题)

现在,我想为我的"filterButton"添加一个监听器.所以一如既往,我以这种方式声明了我的按钮(Button filterButton;),setOnClickListener(在我的onCreate中):

filterButton = (Button) findViewById(R.id.filter_button); 
filterButton.setOnClickListener(filter_listener);
Run Code Online (Sandbox Code Playgroud)

然后我定义我的听众:

OnClickListener filter_listener = new OnClickListener() {

    @Override
    public void onClick(View v) {
//  showPopupMenu(v);
    }  };  
Run Code Online (Sandbox Code Playgroud)

我在里面注释掉了这个方法,以确保问题不是来自这个方法.因此,当我这样做时,当我尝试运行我的应用程序时,它只是在我尝试打开按钮打开alertdialog时的活动时崩溃.当我取下这几行时,它再次起作用.我不明白,它没有意义,它只是一个带有听众的按钮,我有几十个像这样没有问题,所以为什么它在我的警报对话中有问题?

ps:我的logcat像往常一样无用,只是说Fatal Error和nullpointerexception没有细节.

编辑:我改变了如下建议:

filterButton = (Button) alertDialog.findViewById(R.id.filter_button);
filterButton.setOnClickListener(filter_listener);   
Run Code Online (Sandbox Code Playgroud)

我把它放在这里,因为如果放在程序的开头,它是用红色强调alertDialog,但它仍然崩溃:

OnClickListener dialog_listener = new OnClickListener() {

    @Override
    public void onClick(View v) {

        LayoutInflater myLayout = LayoutInflater.from(context);
        View dialogView = myLayout.inflate(R.layout.alertdialog_filter, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);


        Bundle bundle = getIntent().getExtras();
        int filterVariable = bundle.getInt("filterVariable");

        alertDialogBuilder.setTitle("Filter Mode");

          alertDialogBuilder.setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });


        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });  

        // set alertdialog_filter.xml to alertdialog builder
        alertDialogBuilder.setView(dialogView);

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        filterButton = (Button) alertDialog.findViewById(R.id.filter_button);
        filterButton.setOnClickListener(filter_listener);



        // show it
        alertDialog.show();
    }
};   
Run Code Online (Sandbox Code Playgroud)

不同的是,现在它在我打开活动时没有崩溃,但是当我点击应该打开alertdialog的按钮时.

Raj*_*ddy 13

您必须从对话框XML文件中获取按钮,如下面的代码所示

filterButton = (Button) dialog.findViewById(R.id.filter_button); 
Run Code Online (Sandbox Code Playgroud)