
为啥不能直接在Activity中使用findViewById方法获得CheckBox对象
在书上看到【不能直接在Activity中使用findViewById方法获得CheckBox对象】这句话,实在是想不通啊它的checkbox没有放在main.xml里面而...
在书上看到【不能直接在Activity中使用findViewById方法获得CheckBox对象】这句话,实在是想不通啊
它的checkbox没有放在main.xml里面而是另外写一个checkbox.xml 展开
它的checkbox没有放在main.xml里面而是另外写一个checkbox.xml 展开
2个回答
展开全部
你说的那个findViewById方法之前,应该还有一句话代吧 setContentView(R.layout.main);
findViewById只能获取到在R.layout.main这个xml文件定义的组件 而那个checkbox没有放在main.xml里面而是另外写一个checkbox.xml,所以获取不到。
还有一种动态加载布局的方法
LayoutInflater flater = LayoutInflater.from(this);
View view = flater.inflate(R.layout.example, null);
加载布局文件之后,就能获取到布局文件中的组件了
button = (Button) view.findViewById(R.id.button);
textView = (TextView)view.findViewById(R.id.tview);
findViewById只能获取到在R.layout.main这个xml文件定义的组件 而那个checkbox没有放在main.xml里面而是另外写一个checkbox.xml,所以获取不到。
还有一种动态加载布局的方法
LayoutInflater flater = LayoutInflater.from(this);
View view = flater.inflate(R.layout.example, null);
加载布局文件之后,就能获取到布局文件中的组件了
button = (Button) view.findViewById(R.id.button);
textView = (TextView)view.findViewById(R.id.tview);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询