现在的位置: 首页 > 综合 > 正文

Inflate用法!!!i

2017年12月17日 ⁄ 综合 ⁄ 共 1235字 ⁄ 字号 评论关闭

inflate就相当于将一个xml中定义的布局找出来.

因为在一个Activity里如果直接用findViewById()的话,对应的是setConentView()的那个layout里的组件.

此如果你的Activity里如果用到别的layout,比如对话框上的layout,你还要设置对话框上的layout里的组件(像图片ImageView,文字TextView)上的内容,你就必须用inflate()先将对话框上的layout找出来,然后再用这个layout对象去找到它上面的组件,如:
  
  View view=View.inflate(this,R.layout.dialog_layout,null);
  
  TextView dialogTV=(TextView)view.findViewById(R.id.dialog_tv);
  
  dialogTV.setText("abcd");
  
  如果组件R.id.dialog_tv是对话框上的组件,而你直接用this.findViewById(R.id.dialog_tv)肯定会报错.

三种方式可以生成LayoutInflater:
  
  LayoutInflater inflater=LayoutInflater.from(this);
  
  LayoutInflater inflater=getLayoutInflater();
  
  LayoutInflater inflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);

 
  然后调用inflate方法将xml布局文件转成View
  

 
在View类中,也有inflate方法

  
  public static View inflate(Context context,int resource,ViewGroup root)
  
  public View inflate(int resource,ViewGroup root,boolean attachToRoot)
  

public View inflate (int resource, ViewGroup root, boolean attachToRoot) 
  resource:View的layout的ID
  root:如果null,则将此View作为根,此时既可以应用此View中的其他控件了。
           如果!null, 则将默认的layout作为View的根。
  attachToRoot:
  ture:也就将此解析的xml作为View根
  fase:则为默认的xml,做为根视图View

attachToRoot 的作用:是否把选取的视图加入到root中。false
的意思就是不添加到root中。可能需要我们手动添加。

参考链接:http://www.cnblogs.com/yuxing/archive/2012/02/18/2357740.html



抱歉!评论已关闭.