AlertDialog 修改文本内容的颜色

来源:互联网 发布:武汉大学法律硕士 知乎 编辑:程序博客网 时间:2024/05/16 05:57

最近遇到一个问题在联想A858T白色手机上测试如下AlertDialog时,AlertDialog背景默认为白色,title 、message为黑色,但是CheckBox的Text却为白色。


final CheckBox cb = new CheckBox(this);            cb.setChecked(false);            cb.setText(getResources().getString(R.string.close_wifi_switch));            dialog = new AlertDialog.Builder(this)                    .setTitle(getResources().getString(R.string.exit_wimo_sure))                    .setView(cb)                    .setNegativeButton(R.string.cancel,                            new DialogInterface.OnClickListener() {                                public void onClick(DialogInterface dialog,                                        int whichButton) {                                    // Do nothing.                                }                            })                    .setPositiveButton(R.string.exit,                            new DialogInterface.OnClickListener() {                                public void onClick(DialogInterface dialog,                                        int whichButton) {                                                                   }                            }).create();            dialog.show();

故想到是否可以用反射方法读取到AlertDialog的title颜色值,并将其赋给CheckBox的TextColor,后在网上找到相关的AlertController类,这个类是AlertDialog的实现类,是没有对外公开的,然后在这个类中有个私有成员变量叫mTitleView,这个就是AlertDialog的title的TextView,所以只要得到这个成员变量的实例,即可得到title的颜色值


 dialog.show();// 很重要,在执行下列操作之前一定要先执行        try {            Field mAlert = AlertDialog.class.getDeclaredField("mAlert");            mAlert.setAccessible(true);            Object alertController = mAlert.get(dialog);            Field mTitleView = alertController.getClass().getDeclaredField(                    "mTitleView");            mTitleView.setAccessible(true);            TextView title = (TextView) mTitleView.get(alertController);            ColorStateList colorStateList = title.getTextColors();            cb.setTextColor(colorStateList);        } catch (NoSuchFieldException e) {            e.printStackTrace();        } catch (IllegalArgumentException e) {            e.printStackTrace();        } catch (IllegalAccessException e) {            e.printStackTrace();        }

类似于修改checkBox的Text颜色,也可以直接修改AlertDialog的title字体颜色,title.setTextColor(XXXXX)

0 0