從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