Android之Inflate()方法用途+setContentView和inflate区别
引用:http://blog.chinaunix.net/uid-27024249-id-3304935.html
Android之Inflate()方法用途
Inflate()作用就是將xml定義的一個布局找出來并隱藏起來,并沒有顯示出來。
android上還有一個與Inflate()類似功能的方法叫findViewById(),二者有時均可使用,但也有區(qū)別,
區(qū)別在于:
如果你的Activity里用到別的layout,比如對話框layout并且你還要設(shè)置這個layout上的其他組件的內(nèi)容,你就必須用inflate()方法先將對話框的layout找出來,然后再用findViewById()找到它上面的其它組件。例如:
View view1=View.inflate(this,R.layout.dialog_layout,null);
TextView?dialogTV=(TextView)view1.findViewById(R.id.dialog_tv);
dialogTV.setText("abcd");
注:R.id.dialog_tv是在對話框layout上的組件,而這時若直接用this.findViewById(R.id.dialog_tv)肯定會報錯。
所以,Inflate()或可理解為“隱性膨脹”,隱性擺放在view里,在inflate()之前只是獲得控件,但沒有大小也沒有在View里占據(jù)空間;在inflate()之后有了一定大小,但是處于隱藏狀態(tài)。
?
setContentView和inflate區(qū)別
一般用LayoutInflater做一件事:inflate
inflate這個方法總共有四種形式(見下),目的都是把xml表述的layout轉(zhuǎn)化為View對象。
其中有一個比較常用,View inflate(int resource, ViewGroup root),另三個和這個差不多。
int resource,也就是resource/layout文件在R文件中對應(yīng)的ID,這個必須指定。
ViewGroup root,可以是null:null時就只創(chuàng)建一個resource對應(yīng)的View;不是null時:會將創(chuàng)建的view自動加為root的child。
?
setContentView和inflate區(qū)別:
setContentView()一旦調(diào)用, layout就會立刻顯示UI;而inflate只會把Layout形成一個以view類實現(xiàn)成的對象,有需要時再用setContentView(view)顯示出來。一般在activity中通過setContentView()將界面顯示出來,但是如果需要在非activity中對控件布局進(jìn)行設(shè)置,這就需LayoutInflater來進(jìn)行動態(tài)加載了。
?
點擊(此處)折疊或打開
?
?
點擊(此處)折疊或打開
?
?
點擊(此處)折疊或打開
inflate方法總共有四種形式用來把xml表達(dá)的layout轉(zhuǎn)化為view.
?
? ? ? ?This class is used to instantiate layout xml files into its corresponding view object. It is never be used directly——use getLayoutInflater() or getSystemService(String)getLayoutInflate() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up that is already hook up to the current context and correct configured for the device you are running on.?
1. Context.public abstract object getSystemService(String name)?
2. 兩種獲得LayoutInflater的方法?
a. 通過SystemService獲得?
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLEATER_SERVICE);?
b. 從給定的context中獲取?
Public static LayoutInflater from(Context context)?
c. 兩者的區(qū)別:實際上是一樣的,舉例如下:
點擊(此處)折疊或打開
? ? ? ?linearLayout.addView(place_type_text);? 5. findViewById有兩種形式?
R.layout.xx是引用res/layout/xx.xml的布局文件(inflate 方法),R.id.xx是引用布局文件里面的組件,組件的id是xx(findViewById方法)。所有的組件id都能用R.id.xx來查看,但是組件不在setContentView()里面的layout中就無法使用,Activity.findViewById()會出現(xiàn)空指針異常?
a. activity中的findViewById(int id)?
b. View 中的findViewById(int id)?
6.不同點是LayoutInflater是用來找layout下xml布局文件,并且實例化!而findViewById()是找具體xml下的具體widget控件(如:Button,TextView等)。? 個人總結(jié):上面那句話說得很好,inflator是用來實例化layout下的xml文件的,findViewById()是尋找對應(yīng)id的widget控件的。個人把inflator看成是xml文件的句柄,用來抽象地引用這個文件。因為默認(rèn)的inflator對應(yīng)的Context就是目前setContentView對應(yīng)的這個Layout所在的xml文件。
轉(zhuǎn)載于:https://www.cnblogs.com/sode/archive/2013/02/19/2916411.html
總結(jié)
以上是生活随笔為你收集整理的Android之Inflate()方法用途+setContentView和inflate区别的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VS2010中使用JSONCPP方法
- 下一篇: windows8中的数据上下文和简单的L