android 中 修改AlertDialog 样式方法记录

项目设计需求更换原生AlertDialog的样式,基本风格还是按照原生的来,
就是背景、字体大小和颜色这些不能与主体设计冲突

有以下几种方案

1. 通过反射修改Title和message的样式,(按钮可以直接获取到)

AlertDialog源码中,有一个AlertController,在里面可以看到这样的几个控件


于是,我们就可以想办法拿到这些控件,然后给它设置样式了

AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("我是Title")
        .setMessage("我是message")
        .setPositiveButton("确定", null)
        .setNegativeButton("取消", null)
        .create();
dialog.show();
//必须在调用show方法后才可修改样式
try {
    Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
    mAlert.setAccessible(true);
    Object mController = mAlert.get(dialog);
    Field mMessage = mController.getClass().getDeclaredField("mMessageView");
    mMessage.setAccessible(true);
    TextView mMessageView = (TextView) mMessage.get(mController);
    mMessageView.setTextColor(Color.RED);//message样式修改成红色
    // title 同理
    Field mTitle = mController.getClass().getDeclaredField("mTitle");
    mMessage.setAccessible(true);
    TextView mTitleView = (TextView) mMessage.get(mController);
    mMessageView.setTextColor(Color.MAGENTA);//title样式修改成``色
} catch (IllegalAccessException e) {
    e.printStackTrace();
} catch (NoSuchFieldException e) {
    e.printStackTrace();
}
//直接获取按钮并设置
final Button pButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);//确认按键
pButton.setTextColor(Color.GREEN);
pButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        pButton.setText("点过了");
        pButton.setTextColor(Color.MAGENTA);
    }
});
Button nButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);//取消
nButton.setTextColor(Color.BLUE);

跑出来是这样的效果:

这个方法基本达到要求了,如果需要改背景,就要用另外一种粗暴的方法了。


2. 自己写一个layout设置为AlertDialog的子view

这个方法很简单,就不贴代码了

核心方法 dialog.setView();


3. style文件中定义

style文件如下,其中


代码中调用style

AlertDialog dialog = new AlertDialog.Builder(this, R.style.MyDialogStyle)
                .setTitle("我是Title")
                .setMessage("我是message")
                .setPositiveButton("确定", null)
                .setNegativeButton("取消", null)
                .create();
        dialog.show();

也可直接在AppTheme中指定dialog样式@style/MyDialogStyle

效果图出来,怎么message的文字大小变不了呢?
还是通过AlertDialog源码中的AlertController找到 mMessageView的资源文件:


看到这里是使用了android的textAppearanceMedium的style属性。

sdk~\data\res\layout\alert_dialog.xml

找到android的 textAppearance属性集:

sdk~\data\res\values\styles

在TextAppearance中,可以看到,textColor是指向?textColorPrimary,所以上面我们可以通过android:textColorPrimary 来定义颜色属性,而textSize是写的固定尺寸,这样的话...就没办法在style里直接修改了。

暂时想到的办法还是结合反射的方式修改。


项目里面用的话,可以先写一个工具类方便使用.

你可能感兴趣的:(android 中 修改AlertDialog 样式方法记录)