是否可以从其他布局初始化视图? [英] Is it possible to initialize a View from different Layout?
本文介绍了是否可以从其他布局初始化视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Activity
,并与它关联了 layout
.另外,我还有另一个 layout
和一些 Views
.我想使用来自独立 layout
的 View
从我的 Activity
中初始化变量( TextView
).我总是得到 null
.
I have an Activity
and associated with it layout
. Also I have another layout
with some Views
. I want to initialize a variable (TextView
) from my Activity
using a View
from that standalone layout
. I always get null
.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button); // This is OK
// because R.id.button is from R.layout.main layout
tvOne = (TextView) findViewById(R.id.first_item); // This is not OK
// because R.id.first_item is from another layout.
}
推荐答案
这是正确的行为,因为 findViewById()
仅搜索传递给 setContentView的视图层次结构中设置的视图()
This is the correct behaviour, because findViewById()
will only search for views set in the view hierarchy passed to setContentView()
这篇关于是否可以从其他布局初始化视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文