安卓原生AlertDialog修改样式

2018-04-16  本文已影响983人  我是少年520
AlertDialog.png

通过反射和原生的接口修改AlertDialog的样式

AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("提示")
                        .setMessage("你确认删除本选项吗?")
                        .setPositiveButton("确定", new DialogInterface
                                .OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO: 2018/4/16 positive
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface
                                .OnClickListener
                                () {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO: 2018/4/16 negative
                            }
                        })
                        .create();
                alertDialog.show();

                alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(Color.RED);
                alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.GRAY);
                try {
                    Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                    mAlert.setAccessible(true);
                    Object mAlertController = mAlert.get(alertDialog);
                    Field mMessage = mAlertController.getClass().getDeclaredField("mMessageView");
                    mMessage.setAccessible(true);
                    TextView mMessageView = (TextView) mMessage.get(mAlertController);
                    mMessageView.setTextColor(Color.BLACK);
                    Field mTitle = mAlertController.getClass().getDeclaredField("mTitleView");
                    mTitle.setAccessible(true);
                    TextView mTitleView = (TextView) mTitle.get(mAlertController);
                    mTitleView.setTextColor(Color.BLACK);
                    mTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                }
上一篇下一篇

猜你喜欢

热点阅读