2012-11-25 19 views
0

我不完全理解LayoutInflater功能,雖然我在我的項目中使用它。對於我來說,只是爲了找到視圖時,我不能叫findViewById法的方式進行。但有時它不會像我所期望的那樣工作。什麼等同於在Android中使用LayoutInflater的findViewById?

我有這個非常簡單的佈局(main.xml中)

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:orientation="vertical" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       android:id="@+id/layout"> 
    <TextView 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:text="Hello World, MyActivity" 
      android:id="@+id/txt"/> 

    <Button android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Change text" 
      android:id="@+id/btn"/> 
</LinearLayout> 


我要的很簡單 - 只需按下按鈕時,將裏面的TextView文本。一切正常,像這樣

public class MyActivity extends Activity implements View.OnClickListener { 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Button btn = (Button) findViewById(R.id.btn); 
     btn.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View view) { 
     TextView txt = (TextView) findViewById(R.id.txt); 
     double random = Math.random(); 
     txt.setText(String.valueOf(random)); 
    } 
} 

但我想知道這將是等效採用LayoutInflater?我試過這個,但沒有成功,TextView並沒有改變它的值

@Override 
public void onClick(View view) { 
    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    View main = inflater.inflate(R.layout.main, null); 
    TextView txt = (TextView) main.findViewById(R.id.txt); 
    double random = Math.random(); 
    txt.setText(String.valueOf(random)); 
} 

但是當調試時我可以看到每個變量填充正確的值。我的意思是TXT變量實際上包含TextView的哪個值的「Hello World,MyActivity」,經過的setText方法它包含了一些隨機數,但我看不出這種變化對UI。這是我在項目中面對LayoutInflater時遇到的主要問題 - 出於某種原因,我無法更新虛擬視圖。爲什麼?

回答

3

對我來說,這只是一種查找視圖的方法,當我無法調用findViewById 方法時。

這是不正確。所述LayoutInflater被用於膨脹(構建)從所提供的XML佈局文件的圖的層次結構。有了您的第二代碼片段構建從佈局文件(R.layout.main)視圖層次結構,找到從充氣鑑於TextView並設置文本就可以了。問題是這個膨脹的視圖沒有附加到Activity的Visibile UI。你可以看到的變化,例如,如果您再次調用setContentView這個時候給它充氣視圖。這會讓你的Activity的內容是新充氣View

LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View main = inflater.inflate(R.layout.main, null); 
TextView txt = (TextView) main.findViewById(R.id.txt); 
double random = Math.random(); 
txt.setText(String.valueOf(random)); 
setContentView(main); 
+0

感謝。是的,我知道我錯了,這就是我問這個問題的原因。那麼,如果不使用setContentView方法,就不可能使用LayoutInflater更新視圖? –

+0

@VitaliiKorsakov是的,這是不可能的。 'LayoutInflater'將使用'inflate'方法創建新的視圖,所以你沒有「連接」(或者如果你喜歡的話可以引用)到已經存在於'Activity'佈局中的舊視圖。 – Luksprog

相關問題