2012-07-11 18 views
4

我努力開發出一種聰明的方法來清理Blah blah = (Blah) this.findViewById(R.id.blah)堆,否則會污染我的小Activity的字段和onCreate()方法,爲此,我覺得我不應該使用setContentView(),而是使用getViewInflate ).inflate()用於在XML中定義的每個View。Android:setContentView()== getViewInflate()。inflate()?

Activity.setContentView()是一種語法糖,它幾乎重複getViewInflate().inflate()爲每個視圖上的XML?我讀了一些說,好像他們是一樣的。

如果我可以通過查看代碼得到答案,請告訴我。我檢查了Activity.class,但只發現了評論。

+1

getViewInflate()方法在哪裏?我沒有看到它在http://developer.android.com/reference/android/app/Activity.html – fiddler 2012-07-11 09:50:21

+0

對不起,它應該是'ViewInflate.inflate()'。 – Quv 2012-07-11 10:22:08

回答

2

您Activity上的setContentView實際上會調用活動使用的窗口上的setContentView,這本身不僅僅是擴展布局。

你可以做的是使用反射將視圖映射到類字段。你可以下載一個工具類on Github這樣做。

它將解析佈局中聲明的所有視圖,然後嘗試在您的R.id類中找到與該ID相對應的名稱。然後,它會嘗試在目標對象中找到具有相同名稱的字段,並將其設置爲相應的視圖。

例如,如果你有這樣

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 
</LinearLayout> 

佈局它會自動在你的活動映射到textView1場。

+0

謝謝。他們真的很有趣。對我來說,一個問題是它的性能,也許是因爲它調用了一個方法來搜索屬於android.R.id.content的'ViewGroup'的每個'View'。也許我會避免使用'setContentView()'並定義我自己的方法,以便每次執行'ViewInflate.inflate()'時都可以將'View'賦值給變量。 – Quv 2012-07-16 13:47:52

-1

其實你是對的,有兩種方法可以實現同樣的事情:

1)setContentView(R.layout.layout);

2)

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View v = inflater.inflate(R.layout.layout, null); 
setContentView(v); 

你決定什麼更適合你。希望這可以幫助。

+0

對不起,我真的模糊的問題。我懷疑,在'setContentView()'方法的定義中,實際上使用了'ViewInflate.inflate()',並且想知道它是這種情況。我應該詳細說明一下我的問題,也許...... – Quv 2012-07-11 10:22:55

0

我發佈我的可憐的研究。總之,Activity.setContentView()代表PhoneWindow.setContentView()(唯一的具體類Window)其中LayoutInflater.inflate()被稱爲,所以說,「setContentView() == ViewInflate().inflate()」是不是太過分了,我猜。

public class Activity extends { 

    private Window mWindow; 

    public void setContentView(int layoutResID) { 
     getWindow().setContentView(layoutResID); 
     initActionBar(); 
    } 

    public Window getWindow() { 
     return mWindow; 
    } 
} 



public class PhoneWindow extends Window { 

    private LayoutInflater mLayoutInflater; 

    @Override 
    public void setContentView(int layoutResID) { 
     if (mContentParent == null) { 
      installDecor(); 
     } else { 
      mContentParent.removeAllViews(); 
     } 
     **mLayoutInflater.inflate(layoutResID, mContentParent);** 
     final Callback cb = getCallback(); 
     if (cb != null) { 
      cb.onContentChanged(); 
     } 
    } 
} 
相關問題