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(..),就可以獲取到相應控件對象了

 

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