在对话框中设置按钮背景?

lom*_*mza 5 xml android

我有一个对话框,对我来说效果很好,但我想在此对话框中为两个按钮设置背景.它的结构非常复杂,所以我不想将它重写为自定义对话框.但在这种情况下,是否有可能设置背景(更具体地说,有没有办法将样式设置为正/负/中性按钮)?

Fem*_*emi 15

从根本上说,您想要访问对话框按钮:这些(在标准的AlertDialog上)当前有android.R.id.button1正面,android.R.id.button2负面和android.R.id.button3中性的ID .

例如,要在中性按钮上设置背景图像,您可以执行以下操作:

Dialog d;
//
// create your dialog into the variable d
//
((Button)d.findViewById(android.R.id.button3)).setBackgroundResource(R.drawable.new_background);
Run Code Online (Sandbox Code Playgroud)

编辑:如果您使用AlertDialog.Builder创建它.据我所知,这些按钮分配可能会在将来发生变化,因此请记住这一点.

编辑:下面的代码块应该生成看起来像你想要的东西.事实证明,你必须在更改背景之前调用show

AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("TEST MESSAGE)
        .setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        })
        .setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
((Button)alert.findViewById(android.R.id.button1)).setBackgroundResource(R.drawable.button_border);
Run Code Online (Sandbox Code Playgroud)