Android - 如何在alertdialog中应用按钮聚焦和按钮按下是或否按钮

时间:2014-10-04 07:49:22

标签: android button alertdialog

当按下后退按钮时,我有一个用于退出应用程序的警报对话框。我想在Alertdialog中应用Button Focused和Button Pressed为Yes或No按钮。我已经在我的应用程序中为其他按钮应用了Button Focused和Button Pressed。

public void onBackPressed() {
    // TODO Auto-generated method stub
    createDialog();
}

private void createDialog() {
    // TODO Auto-generated method stub
    AlertDialog.Builder alertdlg = new AlertDialog.Builder(this);
    alertdlg.setMessage("Are you sure you want to exit?");
    alertdlg.setCancelable(false);
    alertdlg.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

            Myactivity.super.onBackPressed();

        }
    });
    alertdlg.setNegativeButton("No", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub

        }
    }); 

    alertdlg.create().show();

 }

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码:

// your code

AlertDialog dialog = alertdlg.create();
dialog.show();

Button b = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
if(b != null)
{

 int sdk = android.os.Build.VERSION.SDK_INT;
 if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
       b.setBackgroundDrawable(getResources().getDrawable(R.drawable.your_selector));
 } else {
       b.setBackground(getResources().getDrawable(R.drawable.your_selector));
   }
}

或者您可以创建自定义视图并显示

有关详细信息,请参阅This question