Android通过findViewById()获取控件为NULL


如果在activity中直接调用findViewById方法,它的完整形式是this.findViewById().而我所需要的控件是不存在本身activity的布局中的.所以要通过控件所在的view调用findViewById方法,就可以获取到正确的控件了

怎么获取控件所在的View呢

使用:LinearLayout view= (LinearLayout) inflater.inflate(int resource, ViewGroup root);
//resource 表示控件所在的布局文件在R.java中的标识 eg:  R.layout.activity_main;
//root 表示View的容器  直接写null


其中inflater的创建方式的三种:

                       1.LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                       2.LayoutInflater inflater = Activity.getLayoutInflater();
                       3.LayoutInflater inflater = LayoutInflater.from(Context);


 View view=LayoutInflater.from(this).inflate(
                R.layout.busi_about_task_list, null);
        


最后,通过view.findViewById(..),就可以获取到相应控件对象了

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章