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

时间:2014-12-04 22:59:51

标签: android alertdialog android-alertdialog

如何解除我的自定义对话框?我在.cancel().dismiss()时收到错误,好像它们未在原生.setpositive/Negative button之外解决

尝试this回答,但仍无效......

这是我的对话框代码:

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 个答案:

答案 0 :(得分: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();