2012-09-06 41 views
0

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是否只提供一個靜態實例?

+1

是什麼這個問題的呢? 'findViewById'將返回給定id的第一個'View'的實例,所以如果你在同一個視圖中搜索,並且你給出相同的id,你會得到相同的視圖 – Selvin

+0

我只是混淆了爲什麼我在2個實例中得到相同的結果。現在我懂了。 – R4j

回答

4

你可以很容易地發現你在調試器中獲得完全相同的對象(變量 - >值列 - > Id) 它不是一個STATIC對象,它只是一個單一的對象,當你得到一個活動的實例時,該視圖的視圖將僅在重新創建活動時重新創建。

換句話說,直到重新創建活動時,當您撥打findViewById時,總是會獲得相同的對象,所以更好的做法是在onCreate()中獲取一次,然後重新使用變量。

+0

好的,我明白了。我只是混淆了爲什麼我在兩個實例中得到相同的結果。非常感謝 – R4j

3

txt2txt1same Id意味着TextView相同的對象,它的ID作爲txt所以這種行爲是必然要發生的

相關問題