【问题标题】:Android Close Alert Dialog box and Activity togetherAndroid关闭警报对话框和Activity一起
【发布时间】:2016-05-13 18:30:51
【问题描述】:

在我的 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();

}
}
}

【问题讨论】:

  • 显示您的 OnBackPressed 代码
  • 如果您在onBackPressed() 中调用finish(),它将完成活动。

标签: android android-activity android-alertdialog


【解决方案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;
        }
    });

这可能会对你有所帮助。

【讨论】:

  • 有一个 layoutinflator 和视图。我想我需要关闭该视图,然后关闭活动
  • 是的,尝试关闭视图然后关闭活动。
  • 你知道怎么做吗
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您可以将 onBackPressed() 方法重写为:

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

    【讨论】:

      猜你喜欢
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 2018-07-22
      • 2018-04-11
      • 1970-01-01
      相关资源
      最近更新 更多