最近遇到一個問題在聯想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)