LayoutInflater作用及使用

来源:互联网 发布:ff14l雷霆捏脸数据 编辑:程序博客网 时间:2024/05/17 11:05
作用:用来实例化一个XML文件到指定View中。与findViewById类似,不同的是LayoutInflater找的layout文件下的没有被载入或需动态被载入,

对于已经载入的Activity可以使用findViewById来获得其中的界面元素。
 
获得LayoutInflater的几种方式:
  1. 1.LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater() Returns LayoutInflater The shared LayoutInflater.2.LayoutInflater inflater =LayoutInflater.from(context);//Obtains the LayoutInflater from the given context.3.LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);//A LayoutInflater for inflating layout resources in this context
从源码得到三种都是调用Context.getSystemService(),它根据NAME来取得对应的Object然后转换成相应服务对象。
http://developer.android.com/reference/android/content/Context.html#getSystemService(java.lang.String)
LAYOUT_INFLATER_SERVICELayoutInflater取得xml里定义的view。
 
返回View:
使用inflate方法。
inflate的作用是将一个XML中定义的布局找出来。
Resource:要加载的布局文件的id
root:给加载好的布局添加一个父布局
  1. View view = inflater.inflate(R.layout.newview, null);setContentView(view);//显示
 
0 0