Xml转换成view的原理

本文探讨了在Android开发中,如何使用View.inflate()方法正确加载XML布局,特别是如何处理布局参数。通过分析源码,解释了当attachToRoot参数为true和false时的不同行为,强调了正确设置此参数以确保XML中定义的布局属性得以生效的重要性。
摘要由CSDN通过智能技术生成

在开发过程中,我们通常都有在用View.inflate(context, resource, root)方法来创建视图,这个方法非常方便,但是它有个缺点就是没有加载xml 里面设置的布局参数。举个例子创建一个叫ListViewDemo 的工程。它里面主界面布局里面就放置一个listview

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent">

  <ListView
      android:id="@+id/listview"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

 </RelativeLayout>

在activity 中就是获取到listview 控件并给它设置一个适配器

MainActivity .java

package com.itheima.listviewdemo;
    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.view.LayoutInflater;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值