如何更改Fragment的Back按钮事件

时间:2015-03-04 14:03:35

标签: android onclicklistener keylistener

enter image description here

当我点击“返回”按钮时,我想让对话框解除。像这样:

enter image description here

但现在,当我点击后退按钮时,此应用程序退出!这是我在网上找到的方法,但它不起作用!

mBaseView.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_BACK){
                    if (listAdapter.isShow) {
                        cancle();
                        return true;
                    }
                  }
                return false;
            }
        });

2 个答案:

答案 0 :(得分:0)

@Override
public void onBackPressed(){

    AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
    alert.setTitle("Exit Fest");
    alert.setMessage("Are you sure to exit the application?");
    alert.setPositiveButton("YES", new OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();
        }
    });
    alert.setNegativeButton("NO",new OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog dialog =alert.create();
    dialog.show();
}

答案 1 :(得分:0)

试试这个......

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
       yourdialog.dismiss();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}