无法使用自定义按钮关闭对话框

4
我要如何取消我的自定义对话框?使用 .cancel().dismiss() 会出现错误,好像它们在原生的 .setpositive/Negative button 外部无法解析。

我已经尝试了这个答案,但仍然无效。

这是我的对话框代码:

public void showSettingsAlert(){

    final AlertDialog.Builder alertdialog = new AlertDialog.Builder(mcontext);
    LayoutInflater inflater = LayoutInflater.from(mcontext);
    final View customView = inflater.inflate(R.layout.custom_gps,null);
    alertdialog.setView(customView);
    alertdialog.setCancelable(true);
    FlatButton bouton_ok = (FlatButton)customView.findViewById(R.id.custom_ok_button);
    FlatButton bouton_quitter = (FlatButton)customView.findViewById(R.id.custom_cancel_button);

    bouton_ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mcontext.startActivity(intent);


        }
    });
    bouton_quitter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        //to close the whole application : 
            finish();
            System.exit(0);
        }
    });
    alertdialog.show();
}

在我的主机活动中,这是我检查 GPS 是否已启用的方法:
    protected void onResume() {
    super.onResume();
    gps = new GPSTracker(MainActivity.this);
    // check if GPS enabled
    if(gps.canGetlocation() ){
        //stuff...
    }else{
        gps.showSettingsAlert();
    }
}
1个回答

6

AlertDialog.Builder用于构建警告对话框。在此之后,create()方法会返回一个AlertDialog对象,该对象允许您调用dismiss()。

AlertDialog.Builder builder = new AlertDialog.Builder(this);

LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.brush_opts_dialog,null);
builder.setView(dialogView);

closeBtn = (Button)dialogView.findViewById(R.id.close_btn);

final AlertDialog dialog = builder.create();

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

dialog.show();

我仍然无法关闭对话框final AlertDialog dialog = alertdialog.create(); bouton_ok.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mcontext.startActivity(intent); dialog.cancel(); } }); - RidRoid
没有 :/ 对话框就是不关闭...但是当我把原生的setpositivebutton放回去后,对话框会在我点击“设置”按钮后立即关闭。我认为这是因为setpositivebutton有new DialogInterface.OnClickListener()。在我的自定义按钮上,我有new View.OnClickListener()。你觉得呢,Farouk? - RidRoid
1
我的错!我展示的是构建器而不是AlertDialog本身! - RidRoid
同样的问题,非常令人沮丧!浪费了很多时间,真的必须注意构建器的create()与对话框的create()之间的区别。和你一样,我也是用RidRoid解决了这个问题。 - David Airapetyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接