AlertDialog修改title,message,button样式 空指针问题

AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("Title").setMessage("Message").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        }).create();
        alertDialog.show();
    //这里一定要注意,button的操作一定要写在 alertDialog.show();后面
    //这里一定要注意,button的操作一定要写在 alertDialog.show();后面
    //这里一定要注意,button的操作一定要写在 alertDialog.show();后面
        Button btnPositive =
                alertDialog.getButton(android.app.AlertDialog.BUTTON_POSITIVE);
        Button btnNegative =
                alertDialog.getButton(android.app.AlertDialog.BUTTON_NEGATIVE);
        btnNegative.setTextColor(getResources().getColor(R.color.red));
        btnNegative.setTextSize(18);
        btnPositive.setTextColor(getResources().getColor(R.color.green));
        btnPositive.setTextSize(18);

原因

这里从源码角度简单说一下为什么要放在后面

ctrl+左键点进去之后,下面这样第一段代码
 if (!mCreated) {
            dispatchOnCreate(null);
        }

继续ctrl+左键
 void dispatchOnCreate(Bundle savedInstanceState) {
        if (!mCreated) {
            onCreate(savedInstanceState);  //注意oncreate方法
            mCreated = true;
        }
    }

再瞅一瞅AlertDialog的oncreate()方法
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAlert.installContent();
    }
ctrl+左键
  public void installContent() {
        final int contentView = selectContentView();
        mDialog.setContentView(contentView);
        setupView();
    }
   在setupView()方法中有这个方法
   setupButtons(buttonPanel);
   点击方法发现这个
   mButtonPositive = (Button) buttonPanel.findViewById(android.R.id.button1);
    mButtonPositive.setOnClickListener(mButtonHandler);

这就说明了button的绑定是在show()方法时进行的,所以对button的操作要放到show()方法后面,这样就能避免空指针了
         ```
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,764评论 25 709
  • 铛铛铛,先来说说工作哒吧。 本人哒工作各种悲催哒说。先前哒收银,做了半年多,感觉还行,就是觉哒时间太少叻,而且工...
    趁我未老依然喜欢听趁早阅读 1,105评论 0 1
  • [这是一个典型的案例分析,案例由王红顺校长整理并提供点]:从大数据分析看优等生在中招政治开卷考试中分数差异本真。 ...
    魏金宝阅读 1,261评论 0 0
  • 条件概率术语: s真阳性:患病被检测成 阳 性P(+|L) 假阳性:未患病被检测成阳性P(+|~L) 真阴性:未患...
    Amy酱酱阅读 3,961评论 0 0
  • 8月21日 星期一 晴 今天是特种兵训练第三周第三天,这周学习到的知识点都是满满的干货,非常的实操,但还要...
    Amy莲子阅读 1,618评论 0 5