从findViewById 的文档中:
Look for a child view with the given id. If this view has the given id, return this view.
但我不知道幕后是什么。
例如,如果我有一个TextView
这样的布局 xml:
<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 是否只提供静态实例?