添加自定义view出现空指针异常

时间:2021-01-26 18:18:53
代码片段: 
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);        final View scenemode = inflater.inflate(R.layout.scenemode, null);    new AlertDialog.Builder(MyGridView.this)    .setTitle("情景模式设置")    .setView(scenemode)    .setPositiveButton("ok", null)    .setNegativeButton("cancle", null)     .show();        /*为RadioGroup添加监听事件*/        final RadioButton rb1 = (RadioButton)findViewById(R.id.rb1);        final RadioButton rb2 = (RadioButton)findViewById(R.id.rb2);        final RadioButton rb3 = (RadioButton)findViewById(R.id.rb3);        final RadioButton rb4 = (RadioButton).findViewById(R.id.rb4);        final TextView tv = (TextView)findViewById(R.id.tv);    RadioGroup rg = (RadioGroup)scenemode.findViewById(R.id.rg);        rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {       @Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {if(checkedId == rb1.getId()){

老是报空指针异常,最后发现原来是要
final RadioButton rb1 = (RadioButton)findViewById(R.id.rb1);改为
final RadioButton rb1 = (RadioButton)scenemode.findViewById(R.id.rb1);
以下的几个控件都要改