从findViewById 's document:
Look for a child view with the given id. If this view has the given id, return this view.
findViewById是一个唯一的(静态)实例吗?
但我不知道什么是幕后。
例如,如果我喜欢这个布局XML有TextView
:
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
然后我得到这个TextView的代码:
TextView txt1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txt1 = (TextView)findViewById(R.id.txt);
txt1.setText("Some text");
}
在另一个地方(也许在按钮onClickListener),我得到这个TextView的再次:
((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView txt2 = (TextView) findViewById(R.id.txt);
Log.d(TAG,"txt2: " + txt2.getText().toString());
Log.d(TAG,"txt1: " + txt1.getText().toString());
//Change txt2 text
txt2.setText("aaa");
Log.d(TAG,"txt2: " + txt2.getText().toString());
Log.d(TAG,"txt1: " + txt1.getText().toString());
//change txt1 text
txt1.setText("bbb");
Log.d(TAG,"txt2: " + txt2.getText().toString());
Log.d(TAG,"txt1: " + txt1.getText().toString());
}
});
这里是结果:
txt2: Some text
txt1: Some text
txt2: aaa
txt1: aaa
txt2: bbb
txt1: bbb
你能解释一下吗? findViewById是否只提供一个静态实例?
是什么这个问题的呢? 'findViewById'将返回给定id的第一个'View'的实例,所以如果你在同一个视图中搜索,并且你给出相同的id,你会得到相同的视图 – Selvin
我只是混淆了为什么我在2个实例中得到相同的结果。现在我懂了。 – R4j