经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Android » 查看文章
Android 中的LayoutInflater(布局服务)
来源:cnblogs  作者:yooooooo  时间:2020/12/14 17:02:43  对本文有异议

本节引言:

本节继续带来的是Android系统服务中的LayoutInflater(布局服务),说到布局,大家第一时间 可能想起的是写完一个布局的xml,然后调用Activity的setContentView()加载布局,然后把他显示 到屏幕上是吧~其实这个底层走的还是这个LayoutInflater,用的Android内置的Pull解析器来解析 布局。一般在Android动态加载布局或者添加控件用得较多,本节我们就来学习下他在实际开发中 的一些用法~

1.LayoutInflater的相关介绍

1)Layout是什么鬼?

答:一个用于加载布局的系统服务,就是实例化与Layout XML文件对应的View对象,不能直接使用, 需要通过getLayoutInflater( )方法或getSystemService( )方法来获得与当前Context绑定的 LayoutInflater实例!

2)LayoutInflater的用法

①获取LayoutInflater实例的三种方法:

  1. LayoutInflater inflater1 = LayoutInflater.from(this);
  2. LayoutInflater inflater2 = getLayoutInflater();
  3. LayoutInflater inflater3 = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

PS:后面两个其实底层走的都是第一种方法~

②加载布局的方法:

  1. public View inflate (int resource, ViewGroup root, boolean attachToRoot) 该方法的三个参数依次为:
  2. ①要加载的布局对应的资源id
  3. ②为该布局的外部再嵌套一层父布局,如果不需要的话,写null就可以了!
  4. ③是否为加载的布局文件的最外层套一层root布局,不设置该参数的话, 如果root不为null的话,则默认为true 如果rootnull的话,attachToRoot就没有作用了! root不为nullattachToRoottrue的话,会在加载的布局文件最外层嵌套一层root布局; false的话,则root失去作用! 简单理解就是:是否为加载的布局添加一个root的外层容器~!

③通过LayoutInflater.LayoutParams来设置相关的属性:

比如RelativeLayout还可以通过addRule方法添加规则,就是设置位置:是参考父容器呢? 还是参考子控件?又或者设置margin等等,这个由你决定~

2.纯Java代码加载布局

我们早已习惯了使用XML生成我们需要的布局,但是在一些特定的情况下,我们 需要使用Java代码往我们的布局中动态的添加组件或者布局!

但是不建议大家完全地使用Java代码来编写Android页面布局,首先一点就是代码会多, 一多久容易乱,而且不利于业务的分离,我们还是建议使用xml来完成布局,然后通过 Java代码对里面的组件进行修改,当然有些时候可能需要使用Java动态的来添加组件!

纯Java代码加载布局的流程:

——Step 1:

①创建容器:LinearLayout ly = new LinearLayout(this);

②创建组件:Button btnOne = new Button(this);

——Step 2:

可以为容器或者组件设置相关属性: 比如:LinearLayout,我们可以设置组件的排列方向:ly.setOrientation(LinearLayout.VERTICAL); 而组件也可以:比如Button:btnOne.setText("按钮1"); 关于设置属性的方法可参见Android 的API,通常xml设置的属性只需在前面添加:set即可,比如 setPadding(左,上,右,下);

——Step 3:

将组件或容器添加到容器中,这个时候我们可能需要设置下组件的添加位置,或者设置他的大小: 我们需要用到一个类:LayoutParams,我们可以把它看成布局容器的一个信息包!封装位置与大小 等信息的一个类!先演示下设置大小的方法:(前面的LinearLayout可以根据不同容器进行更改)

  1. LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
  2. LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

很简单,接着就到这个设置位置了,设置位置的话,通常我们考虑的只是RelativeLayout! 这个时候用到LayoutParams的addRule( )方法!可以添加多个addRule( )哦! 设置组件在父容器中的位置,

比如设置组件的对其方式:

  1. RelativeLayout rly = new RelativeLayout(this);
  2. RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
  3. LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  4. lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
  5. Button btnOne = new Button(this);
  6. rly.addView(btnOne, lp2);

参照其他组件的对其方式: (有个缺点,就是要为参考组件手动设置一个id,是手动!!!!) 比如:设置btnOne居中后,让BtnTwo位于btnOne的下方以及父容器的右边!

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. RelativeLayout rly = new RelativeLayout(this);
  6. Button btnOne = new Button(this);
  7. btnOne.setText("按钮1");
  8. Button btnTwo = new Button(this);
  9. btnTwo.setText("按钮2");
  10. // 为按钮1设置一个id值
  11. btnOne.setId(123);
  12. // 设置按钮1的位置,在父容器中居中
  13. RelativeLayout.LayoutParams rlp1 = new RelativeLayout.LayoutParams(
  14. LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  15. rlp1.addRule(RelativeLayout.CENTER_IN_PARENT);
  16. // 设置按钮2的位置,在按钮1的下方,并且对齐父容器右面
  17. RelativeLayout.LayoutParams rlp2 = new RelativeLayout.LayoutParams(
  18. LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  19. rlp2.addRule(RelativeLayout.BELOW, 123);
  20. rlp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
  21. // 将组件添加到外部容器中
  22. rly.addView(btnTwo, rlp2);
  23. rly.addView(btnOne, rlp1);
  24. // 设置当前视图加载的View即rly
  25. setContentView(rly);
  26. }
  27. }

——step 4:

调用setContentView( )方法加载布局对象即可! 另外,如果你想移除某个容器中的View,可以调用容器.removeView(要移除的组件);

运行截图:

image

3.Java代码动态添加控件或xml布局

第二点我们讲解了使用纯Java代码来加载布局,实际当中用得并不多,更多的时候是动态 的添加View控件以及动态的加载XML布局!

1)Java代码动态增加View

动态添加组件的写法有两种,区别在于是否需要先setContentView(R.layout.activity_main); 下面演示下两种不同写法添加一个Button的例子:

先写个布局文件先:activity_main.xml:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:id="@+id/RelativeLayout1"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5. <TextView
  6. android:id="@+id/txtTitle"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:text="我是xml文件加载的布局"/>
  10. </RelativeLayout>

第一种不需要setContentView()加载布局文件先:

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. Button btnOne = new Button(this);
  6. btnOne.setText("我是动态添加的按钮");
  7. RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
  8. LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  9. lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
  10. LayoutInflater inflater = LayoutInflater.from(this);
  11. RelativeLayout rly = (RelativeLayout) inflater.inflate(
  12. R.layout.activity_main, null)
  13. .findViewById(R.id.RelativeLayout1);
  14. rly.addView(btnOne,lp2);
  15. setContentView(rly);
  16. }
  17. }

第二种不需要setContentView()加载布局文件先:

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. Button btnOne = new Button(this);
  7. btnOne.setText("我是动态添加的按钮");
  8. RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
  9. LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  10. lp2.addRule(RelativeLayout.CENTER_IN_PARENT);
  11. RelativeLayout rly = (RelativeLayout) findViewById(R.id.RelativeLayout1);
  12. rly.addView(btnOne,lp2);
  13. }
  14. }

分析总结:

代码很简单,创建按钮后,我们又创建了一个LayoutParams对象,用来设置Button的大小, 又通过addRule()方法设置了Button的位置!

第一种方法:通过LayoutInflate的inflate()方法加载了activity_main布局,获得了外层容器, 接着addView添加按钮进容器,最后setContentView();

第二种方法:因为我们已经通过setContetView()方法加载了布局,此时我们就可以通过 findViewById找到这个外层容器,接着addView,最后setContentView()即可!

另外,关于这个setContentView( )他设置的视图节点是整个XML的根节点!

2)Java代码动态加载xml布局

接下来的话,我们换一个,这次加载的是xml文件!动态地添加xml文件! 先写下主布局文件和动态加载的布局文件:

activity_main.xml:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:id="@+id/RelativeLayout1"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent" >
  5. <Button
  6. android:id="@+id/btnLoad"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:text="动态加载布局"/>
  10. </RelativeLayout>

inflate.xml:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:gravity="center"
  6. android:orientation="vertical"
  7. android:id="@+id/ly_inflate" >
  8. <TextView
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="我是Java代码加载的布局" />
  12. <Button
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:text="我是布局里的一个小按钮" />
  16. </LinearLayout>

接着到我们的MainActivity.java在这里动态加载xml布局:

  1. public class MainActivity extends Activity {
  2. @Override
  3. protected void onCreate(Bundle savedInstanceState) {
  4. super.onCreate(savedInstanceState);
  5. setContentView(R.layout.activity_main);
  6. //获得LayoutInflater对象;
  7. final LayoutInflater inflater = LayoutInflater.from(this);
  8. //获得外部容器对象
  9. final RelativeLayout rly = (RelativeLayout) findViewById(R.id.RelativeLayout1);
  10. Button btnLoad = (Button) findViewById(R.id.btnLoad);
  11. btnLoad.setOnClickListener(new OnClickListener() {
  12. @Override
  13. public void onClick(View v) {
  14. //加载要添加的布局对象
  15. LinearLayout ly = (LinearLayout) inflater.inflate(
  16. R.layout.inflate, null, fa运行截图:
  17. lse).findViewById(
  18. R.id.ly_inflate);
  19. //设置加载布局的大小与位置
  20. RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
  21. LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  22. lp.addRule(RelativeLayout.CENTER_IN_PARENT);
  23. rly.addView(ly,lp);
  24. }
  25. });
  26. }
  27. }

运行截图:

image

代码分析:

①获取容器对象:

  1. final RelativeLayout rly = (RelativeLayout) findViewById(R.id.RelativeLayout1);

②获得Inflater对象,同时加载被添加的布局的xml,通过findViewById找到最外层的根节点

  1. final LayoutInflater inflater = LayoutInflater.from(this);
  2. LinearLayout ly = (LinearLayout) inflater.inflate(R.layout.inflate, null, false)
  3. .findViewById(R.id.ly_inflate);

③为这个容器设置大小与位置信息:

  1. RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
  2. LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  3. lp.addRule(RelativeLayout.CENTER_IN_PARENT);

④添加到外层容器中:

  1. rly.addView(ly,lp);

4.LayoutInflater的inflate()方法源码

最后提供下LayoutInflater的inflate()方法的源码吧,有兴趣的可以看看,其实就是Pull解析而已

  1. public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
  2. synchronized (mConstructorArgs) {
  3. final AttributeSet attrs = Xml.asAttributeSet(parser);
  4. mConstructorArgs[0] = mContext;
  5. View result = root;
  6. try {
  7. int type;
  8. while ((type = parser.next()) != XmlPullParser.START_TAG &&
  9. type != XmlPullParser.END_DOCUMENT) {
  10. }
  11. if (type != XmlPullParser.START_TAG) {
  12. throw new InflateException(parser.getPositionDescription()
  13. + ": No start tag found!");
  14. }
  15. final String name = parser.getName();
  16. if (TAG_MERGE.equals(name)) {
  17. if (root == null || !attachToRoot) {
  18. throw new InflateException("merge can be used only with a valid "
  19. + "ViewGroup root and attachToRoot=true");
  20. }
  21. rInflate(parser, root, attrs);
  22. } else {
  23. View temp = createViewFromTag(name, attrs);
  24. ViewGroup.LayoutParams params = null;
  25. if (root != null) {
  26. params = root.generateLayoutParams(attrs);
  27. if (!attachToRoot) {
  28. temp.setLayoutParams(params);
  29. }
  30. }
  31. rInflate(parser, temp, attrs);
  32. if (root != null && attachToRoot) {
  33. root.addView(temp, params);
  34. }
  35. if (root == null || !attachToRoot) {
  36. result = temp;
  37. }
  38. }
  39. } catch (XmlPullParserException e) {
  40. InflateException ex = new InflateException(e.getMessage());
  41. ex.initCause(e);
  42. throw ex;
  43. } catch (IOException e) {
  44. InflateException ex = new InflateException(
  45. parser.getPositionDescription()
  46. + ": " + e.getMessage());
  47. ex.initCause(e);
  48. throw ex;
  49. }
  50. return result;
  51. }
  52. }

本节小结:

本节给大家讲解了一下Android中的LayoutInflater(布局服务),以及动态加载View和控件 相关的东西,相信对初学控件的朋友带来帮助~好的,就说这么多,谢谢

原文链接:http://www.cnblogs.com/linhaostudy/p/14113195.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号