Dialog使用findViewById 报空指针异常

问题描述

​ 创建完成一个Dialog之后,想修改Dialog中某个TextView的值,报空指针异常

    Dialog dialog = new CustomDialog(context);             //自定义Dialog
    TextView textView=dialog.findViewById(R.id.textView1); //该行代码会爆空指针异常
    textView.setText("待显示的UI文本")
    dialog.show();

问题原因

​ 查看Dialog#findViewById源码

   /**
     * Finds a child view with the given identifier. Returns null if the
     * specified child view does not exist or the dialog has not yet been fully
     * created (for example, via {@link #show()} or {@link #create()}).
     *
     * @param id the identifier of the view to find
     * @return The view with the given id or null.
     */
    public View findViewById(int id) {
        return mWindow.findViewById(id);
    }

​ 注释说得很清楚,如果该dialog仍未完全创建好(如果仍未调用 show()create()方法),会返回null

问题解决

​ 调整代码执行顺序,先调用Dialog#show()方法然后调用Dialog#findViewById方法

    Dialog dialog = new CustomDialog(context);             //自定义Dialog
    dialog.show();
    TextView textView=dialog.findViewById(R.id.textView1); 
    textView.setText("待显示的UI文本")
    

你可能感兴趣的:(android,dialog,findViewById,android)