而不是在xml中为id加前缀,是否可以在代码中指定特定的布局?例如,如果我有3个布局,每个布局都带有一个ID为“btn”的按钮。是否可以指定哪个布局来查找ViewById(R.id.btn)?findViewById在特定的布局?
3
A
回答
2
基本上下文通过setContentView(R.lyaout.my_layout)
定义。如果你使用LayoutInflater.inflate()
膨胀另一个布局,你会得到一个布局对象,我们称它为buttonLayout
。您现在可以在this.findViewById(R.id.button)
和buttonLayout.findViewById(R.id.button)
之间有所不同,两者都会为您提供不同的按钮引用。
3
findViewById
是View
类的一种方法。您可以指定视图应该如何搜索的位置
final View container = new View(context);
container.findViewById(R.id.btn);
+0
它也是一个Activity类的方法 – WarrenFaith
0
如果你的内容视图是一个复杂的层次结构与ID btn
多个视图,您需要导航到层次的子树,并从那里寻找。假设您有三个LinearLayout
视图,每个视图中都有一个btn
视图。如果你可以先选择正确的LinearLayout
(通过ID,标签,位置,或其他方式),然后你可以找到正确的btn
视图。如果相关LinearLayout
有branch1
ID,例如:
View parent = findViewById(R.id.branch1); // Activity method
View btn = parent.findViewById(R.id.btn); // View method
0
,如果你有不同的Viewgroups里面你btns,这是可能的,但需要给ViewGroups一个不同的名字! Easyiest将为此目的定义按钮的布局自己的XML内(即button_layout.xml) 你的活动中,你可以这样做:
public MyActivity extends Activity{
Button btn1, btn2, btn3;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
LinearLayout ll = new LinearLayout(this);
setContentView(ll);
btn1 = (Button)inflater.inflate(R.layout.button_layout, ll);
btn2 = (Button)inflater.inflate(R.layout.button_layout, ll);
btn3 = (Button)inflater.inflate(R.layout.button_layout, ll);
}
}
相关问题
- 1. 为特定布局调用findViewById()? NullPointerException on findViewById()
- 2. FindViewById在不同的布局?
- 3. findViewById其他布局
- 4. Android的findViewById为父布局
- 5. findViewById:引用到布局
- 6. findViewByID在Java中的相对布局(Android)
- 7. findViewById从膨胀布局中返回空
- 8. findViewById如下返回null偏好布局
- 9. findViewById返回null从布局查看
- 10. 在UIWebView中显示特定的布局
- 11. Android布局如何设置特定的固定布局高度
- 12. 使用嵌套布局定义特定的xml布局
- 13. 特定布局建议
- 14. 全局引用findViewById
- 15. Xamarin.Forms布局如何转换为平台特定的布局?
- 16. Android - findViewById方法在片段中查找自定义布局中的项目
- 17. Android布局设计特定自定义
- 18. 设计一个特定的布局
- 19. 特定布局的Xcode约束
- 20. 布局与元件的特定位置
- 21. 特定网站的CSS布局
- 22. 访问特定布局的按钮
- 23. 特定的XML布局需要
- 24. 资源特定的设计布局
- 25. Zend针对特定操作的布局
- 26. Zend_Navigation和模块特定的布局
- 27. 使用模型的特定布局
- 28. 启用特定布局的滚动
- 29. 特定的CSS菜单布局
- 30. 针对特定任务的Java布局
它会搜索该ID在您通过膨胀的一个inflate或setcontent查看 – Raykud