android - 为对话框中的按钮设置背景?

标签 android xml

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

最佳答案

基本上你想访问对话框按钮:这些(在标准的 AlertDialog 上)目前有 ids android.R.id.button1 代表积极,android.R.id.button2 表示否定,android.R.id.button3 表示中性。

因此,例如要在中性按钮上设置背景图像,您可以这样做:

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

编辑:如果您使用 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);

关于android - 为对话框中的按钮设置背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5814998/

相关文章:

java - 同时通过蓝牙发送音乐和附加数据?

android - Espresso Dagger 2.11

android - Android 模拟器上没有市场应用程序

xml - 如果节点有时是不同的元素,如何对节点进行编号

java - XML 子节点计数 - Java

java - Android java - 是否可以从 RadioGroup 中的 RadioButton 获取文本,而无需每个 RadioButton 都有定义的 id?

java - USB调试代码

android - 如何修改MPAndroidChart BarChart中的条宽?

c# - 如何从 XmlDocument 中选择具有 XML 命名空间的 XML 节点?

php - 在 PHP 中从 XML 中获取属性