0
点赞
收藏
分享

微信扫一扫

Android原生AlertDialog修改标题,内容,按钮颜色,字体大小等



Android原生AlertDialog修改标题,内容,按钮颜色,字体大小等_自定义

private void showAlerDialog() {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("AlerDialog")
.setMessage("这是一个AlertDialog")
.setPositiveButton("确定",null)
.setNegativeButton("取消",null)
.create();
dialog.show();
}

需求

​AlertDialog​​,其中的标题,内容还有按钮的颜色大小等,系统代码中并没有暴露出方法来允许我们自定义他们,可假如有需求,为了突出确定,需要将确定的按钮修改为红色,我们该怎么做呢,或者是需要修改标题颜色等,当然我们可以选择自定义View,在此处我们不讨论这个方法,我们尝试修改原生的​​AlertDialog​​的标题,按钮颜色等;

分析

修改内容颜色


Android原生AlertDialog修改标题,内容,按钮颜色,字体大小等_控件_02

​AlertDialog​​没有提供修改的方法,那我们可以通过反射来提取到这个控件,然后修改其颜色即可;

public class AlertDialog extends AppCompatDialog implements DialogInterface {

final AlertController mAlert;
...
}

​AlertDialog​​源码我们发现有一个全局的​​AlertController​​,​​AlertDialog​​主要就是通过这个类来实现的,我们继续看这个类的源码;

class AlertController {
...
private ImageView mIconView;
private TextView mTitleView;
private TextView mMessageView;
private View mCustomTitleView;
...

​mTitleView​​,​​mMessageView​​等字段,这些字段就是我们所需要的,我们就可以通过反射来动态修改他们;

private void showAlerDialog() {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("AlerDialog")
.setMessage("这是一个AlertDialog")
.setPositiveButton("确定",null)
.setNegativeButton("取消",null)
.create();
dialog.show();
try {
Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
mAlert.setAccessible(true);
Object mAlertController = mAlert.get(dialog);
Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
mMessage.setAccessible(true);
TextView mMessageView = (TextView) mMessage.get(mAlertController);
mMessageView.setTextColor(Color.BLUE);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}

反射来修改原生​​AlertDialog​​中内容的颜色或者大小;

修改按钮颜色


Android原生AlertDialog修改标题,内容,按钮颜色,字体大小等_字段_03

​AlertDialog​​提供了相应的方法来实现针对按钮的操作,所以我们可以通过以下方法直接调用,例如将按钮的颜色一个修改为黑色,一个修改为蓝色:

private void showAlerDialog() {
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("AlerDialog")
.setMessage("这是一个AlertDialog")
.setPositiveButton("确定",null)
.setNegativeButton("取消",null)
.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
}

​AlertDialog​​中按钮的颜色来自己定义;​​AlertDialog​​的​​show()​​方法后进行,否则会报错;

举报

相关推荐

0 条评论