Android中关于布局填充器的各种详细用法和说明

来源:互联网 发布:银行卡网络异地消费 编辑:程序博客网 时间:2024/05/22 03:12

1.通过系统获取系统的布局管理器,这种方式通常是当我们获取系统的应用或者和系统相关的操作时使用的

 LayoutInflater inflater=(LayoutInflater)Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);如果在Activity中可以省略Context,如果在一个类中就要使用上下文;

View mView=inflater.inflate(Context,R.layout.XX,root);

2.在Activity中要给某个ViewGroup添加子布局时使用以下方式

View  mView=getLayoutInflate.inflate(R.layout.xx,root,false);

3.通过View的静态方式获取,这种通常用在自定义控件中,比如自定义dialog或者toast中都可以使用

View mView=View.inflate(Context,R.layout.xx,false);

4,通过LayoutInflate的inflate()方法来是实现,典型的BaseAdapter中加载布局的方式

View view=LayoutInflater.from(Context).inflate(R.layout.xx,rootView,false);

以上就是Layoutinflate的四种用法。下面简单的通过代码来说一下这四种之间的关系或者本质的区别吧

第一:在Activity中,

public  Layoutinflater getLayoutInflater(){

return getWindow().getLayoutInflater();}

 而Activity在底层还是调用了抽象类Window的方法:

 public LayouInflater getLayoutInflater(Context context){

return  LayoutInflate.from(Context context);

},而window类中是如何调用的呢?请看下面内容

Window是通过静态的方式获取LayoutInflater的

 public   static  View  inflate(Context mContext, LayoutRes  res, ViewGroup root){

LayoutInflater  mLayoutInflater=LayoutInflater.from(mContext);

return mLayoutInflater.inflate(res,root);

}

值得注意的是LayoutInflater也是一个abstract类,它最终还是调用系统的方式获取的

public abstract  LayoutInflater  extends Object{

public static  static  LayoutInflater from(Context mContext){

 LayoutInflater mLayoutInflater=(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if(mLayoutInflater==null){

throws  Exception(Exception e);

}

return  mLayoutInflater;





}

0 0