Android关闭警报对话框和活动在一起

时间:2016-05-12 05:28:26

标签: android android-activity alertdialog

在我的Android应用程序中,我有一个alertdialog框将在创建活动时以sson打开,并根据alertdialog搜索中给出的文本完成,结果显示在列表视图中。但是当我点击后退按钮时,首先关闭警报对话框,然后再次点击后退按钮关闭当前活动。但我需要在一个后退按钮点击关闭警报对话框和活动。我在下面给出代码。

AlertDialog alertDialog;

    public SampleTest() {
        alertDialog = null;
    }


    public void onCreate(Bundle savedInstanceState)

    {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_branch_list);



        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.search_branch_predict, null);

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

        // set prompts.xml to alertdialog builder
        alertDialogBuilder.setView(promptsView);

        final EditText userInput = (EditText) promptsView
                .findViewById(R.id.edittext);

        final Button btnSearch = (Button) promptsView.findViewById(R.id.search_Button);


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

        // show it
        alertDialog.show();

}
}
}

3 个答案:

答案 0 :(得分:1)

在您的活动中覆盖onBackPressed()并检查是否已打开警报对话框,然后调用“完成以终止活动”。

    @Override
   public void onBackPressed() {
    if(alertDialog.isShowing()){
     alertDilaog.dismiss(); // this will dismiss your dialog
     finish(); // this will kill your activity
    }else{
     super.onBackPressed();   
    }
  }

答案 1 :(得分:1)

试试这个,

@Override  
public boolean onKeyDown(int keyCode, KeyEvent event)  
{  
     //replaces the default 'Back' button action  
     if(keyCode==KeyEvent.KEYCODE_BACK)  
     {  

        dialog.dismiss();
        finish();

     }  
     return true;  
}  

@Override
public void onBackPressed() {
    dialog.dismiss();
    finish();
}

编辑1:

LayoutInflater li = LayoutInflater.from(context);
LinearLayout mainLayout = (LinearLayout) li.inflate(R.id.YOUR_LAYOU_ID_HERE, this);

mainLayout.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            int eid = event.getAction();
            switch (eid) {
            case MotionEvent.ACTION_DOWN:
                finish();
                break;
            }
            return true;
        }
    });

这可能对你有所帮助。

答案 2 :(得分:0)

您可以将onBackPressed()方法覆盖为:

 @Override
    public void onBackPressed() {
        alertDialog.dismiss();
        yourActivity.this.finish();
    }