安卓哲学

inflate方法和findViewById方法的区别

2017-05-04  本文已影响128人  大橙喵

1.操作对象


  1. inflate()方法是用来将res/layout/下的xml布局文件实例化,操作对象是XML文件返回ViewGroup对象.
  2. findViewById()是找已被实例化为View对象的xml布局文件下的具体控件(如Button、TextView等),操作对象是一个ViewGroup或者是Activity,返回一个View对象.

2.功能


  1. 对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入
  2. 对于一个已经载入的界面,就可以使用Activity.findViewById()方法来获得其中的界面元素

3.调用方法


  1. LayoutInflater
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null);
LayoutInflater inflater = LayoutInflater.from(context); 
View layout = inflater.inflate(R.layout.main, null); 
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.main, null);
  1. findViewById
//假设已经通过LayoutInflater加载了一个ViewGroup vp
View view = vp.findViewById(R.id.res_id);
//通过强制类型转换转换成你在XML里面定义的对象比如在XML里面定义了一个Button,即可获取到这个Button的对象
Button bt = (Button)view;
上一篇 下一篇

猜你喜欢

热点阅读