android项目Java文件找界面元素findViewById(R.id.*);

   写android的新手都知道,用findViewById()找界面元素,一般默认为this.findViewById(R.id.*);的形式,this为当前的主界面。但是,如果不是主界面对应的xml文件的id时该怎么办呢   ?

   两个视图,一个MainActivity,一个AlertDialog,分别对应着main.xml文件和second.xml文件.

main.xml

 <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button1" />

second.xml

 <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button2" />

在主Activity里使用 Button button1=(Button)this.findViewById(R.id.button1);

在创建对话框的 方法里面 protected Dialog onCreateDialog(int id){

                                        AlertDialog.Builder builder=new AlertDialog.Builder(this);   //Builder为对话框的辅助类

                   View layout=(View)getLayoutInflater().inflate(R.layout.second);

         

                Button   button2=(Button)Layout.findViewById(R.id.button2);

                        builder.setView(layout);

                        ........增加其余信息

               return builder.create();

                                        }

可以发现,如黄色部分,找button1和button2 对应的findViewById方法对应的对象是不同的,一个是this,一个是Layout。如果改成utton2=this.findViewById(R.id.button2);,则android Application找不到对应id,以为主xml文件没有button,系统就会报错,出现空指针异常!所以findViewById在使用前有必要声明是在哪个xml文件里找id。

  这个错误困扰我一段时间了,今天老师才讲,希望与君共勉,一同进步!

猜你喜欢

转载自1509930816.iteye.com/blog/2123287