View.inflate和LayoutInflater的inflate方法区别
平時ListView加載item中,adapter的getView方法中,我們經常用到:
LayoutInflater.from(mContext).inflate(R.layout.it ,parent,false);這樣的方法來加載布局xml,平時一直就是這么用的,也沒什么疑問。今天網上看了個自定義布局的源碼,自定義布局中加載布局xml用的View.inflate方法:
public class SettingItemView extends RelativeLayout { private CheckBox cb_status; private TextView tv_description; private TextView tv_title; private String desc_on; private String desc_off; private void iniView(Context context) { View.inflate(context, R.layout.setting_item_view, this);//第三個參數傳布局文件的父類 cb_status=(CheckBox) this.findViewById(R.id.cb_status); tv_description=(TextView) this.findViewById(R.id.tv_description); tv_title=(TextView) this.findViewById(R.id.tv_title); }第一次見用這種方式來加載布局的,看了下他的listview加載item,也是用這種方式:
@Overridepublic View getView(final int position, View convertView, ViewGroup parent) {View view;ViewHolder holder;if(convertView==null){view=View.inflate(getApplicationContext(), R.layout.list_item_callsms, null);//最后一個傳了null holder=new ViewHolder(); holder.tv_number=(TextView) view.findViewById(R.id.tv_black_number); holder.tv_mode=(TextView) view.findViewById(R.id.tv_black_mode); holder.iv_delete=(ImageView) view.findViewById(R.id.iv_delete); view.setTag(holder);?
好吧,看一下View.inflate的說明:
Open Declaration View android.view.View.inflate(Context context, int resource, ViewGroup root)
Inflate a view from an XML resource. This convenience method wraps the
LayoutInflater class, which provides a full range of options for view
inflation.
Parameters: context The Context object for your activity or
application. resource The resource ID to inflate root A view group
that will be the parent. Used to properly inflate the layout_*
parameters.
See Also: LayoutInflater
最后有一句讓你看LayoutInflater這個類,懷疑它內部也是用LayoutInflater實現的,進入源碼:
果然內部也是用LayoutInflater實現的,不知道為啥android還要用View.inflat封裝一下。。。o(〃’▽’〃)o
其中LayoutInflater的Inflate的三個參數意思為:
對于Inflate的三個參數(int resource, ViewGroup root, boolean attachToRoot)
如果inflate(layoutId, null )則layoutId的最外層的控件的寬高是沒有效果的
如果inflate(layoutId, root, false ) 則認為和上面效果是一樣的
如果inflate(layoutId, root, true ) 則認為這樣的話layoutId的最外層控件的寬高才能正常顯示
對這三個參數區別不理解的話可以看這篇文章:
inflate第三個參數意思
從源碼角度解析的有郭大神的:
Android LayoutInflater原理分析,帶你一步步深入了解View(一)
以及另一篇感覺很不錯的:
Android LayoutInflate深度解析 給你帶來全新的認識
看完,你應該知道這個參數意思了,ok,再來看上面代碼, 這時就可以替換為layoutInflater的方式了:
對于第一個自定義布局:
//View.inflate(context, R.layout.setting_item_view, this);//第三個參數傳布局文件的父類LayoutInflater.from(context).inflate(R.layout.setting_item_view, this, true);//等價于上面第二個適配器中getView:
//view=View.inflate(getApplicationContext(), R.layout.list_item_callsms, null);view=LayoutInflater.from(getApplicationContext()).inflate(R.layout.list_item_callsms,parent,false);轉載于:https://www.cnblogs.com/ldq2016/p/6244780.html
總結
以上是生活随笔為你收集整理的View.inflate和LayoutInflater的inflate方法区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BZOJ 3237: [Ahoi2013
- 下一篇: [已解决] java 增加 ALPN支持