我的应用程序中有很多提醒对话框.这是默认布局,但我正在向对话框中添加正按钮和负按钮.因此,这些按钮的默认文本 colored颜色 为Android 5(绿色).我试着改变它,但没有成功.你知道怎么改变文字 colored颜色 吗?

我的自定义对话框:

public class MyCustomDialog extends AlertDialog.Builder {

    public MyCustomDialog(Context context,String title,String message) {
        super(context);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View viewDialog = inflater.inflate(R.layout.dialog_simple, null, false);

        TextView titleTextView = (TextView)viewDialog.findViewById(R.id.title);
        titleTextView.setText(title);
        TextView messageTextView = (TextView)viewDialog.findViewById(R.id.message);
        messageTextView.setText(message);

        this.setCancelable(false);

        this.setView(viewDialog);

    } }

创建对话框:

MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage);
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ...
                        }
}).show();

NegativeButton是默认的对话框按钮,采用Android 5棒棒糖中的默认绿色.

非常感谢

带有绿色按钮的自定义对话框

推荐答案

您可以先try 创建AlertDialog对象,然后使用它进行设置以更改按钮的 colored颜色 ,然后显示它.(请注意,在builder对象上,我们调用create()来获取AlertDialog对象,而不是调用show():

//1. create a dialog object 'dialog'
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage); 
AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    ...
                }

            }).create();

//2. now setup to change color of the button
dialog.setOnShowListener( new OnShowListener() {
    @Override
    public void onShow(DialogInterface arg0) {
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(COLOR_I_WANT);
    }
});

dialog.show()

您必须在onShow()上执行此操作,并且在创建对话框后不能仅获取该按钮的原因是该按钮尚未创建.

我把AlertDialog.BUTTON_POSITIVE改为AlertDialog.BUTTON_NEGATIVE,以反映你问题中的变化.虽然奇怪的是"OK"按钮会是一个负按钮.通常是正面按钮.

Android相关问答推荐

未解析的引用:背景 colored颜色

如何go 除回调流中不可用的状态?

当X为lambda函数时,如何避免Android Studio错误检测参数X未使用?

如何在Jetpack Compose中使用Box Composable来实现这种布局?

Jetpack创作动画断断续续变化的观点

保护所有程序包文件和类

属性可选的涟漪效果ItemBackEarth Borderless不适用于Android 13和更高版本

在Jetpack Compose中,如何判断屏幕是否已重新组合?

Android-LVL库始终返回NOT_SUBLISTED

学习Kotlin问题.无法理解Modifier参数

从不可组合回调打开可组合屏幕

在 kotlin 上向适配器添加绑定视图功能

了解 CoroutineScope(Job() + Dispatchers.Main) 语法

为什么 Android Studio 中的 theme.xml 目录没有任何原色

在 compose 中做可变状态堆栈

在 jetpack compose 中交替使用 View.INVISIBLE

在compose中,为什么修改List元素的属性,LazyColumn不刷新

在 Kotlin 中循环遍历字符串并用新行替换句号

将应用更改为暗模式后 Android MainActivity 数据泄漏

Android Jetpack Compose - 每次文本字段值更改时,可组合函数都会重新组合