浅谈安卓中的LayoutInflater

本文详细介绍了LayoutInflater在Android开发中的作用及使用方法,特别是在BaseAdapter的getView方法中的应用。通过具体实例展示了如何利用LayoutInflater动态加载布局文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在之前的安卓学习中每次编写程序想必都会用到findViewById(),这个方法,我们都知道它是用来获取某个已经定义好的控件后对其作相应的操作。其实LayoutInflater与findViewById()的作用类似,只不过LayoutInflater不是用来获取控件的,而是用来获取布局对象的。
在大多数的开发过程中,我们前面定义好的布局文件都不能时刻满足我们的实际需求,这句需要我们动态的在代码中改写布局文件,这是就要用到LayoutInflater。LayoutInflater在在网上查找LayoutInflater,在安卓中是扩展的意思。其最常用的地方是在BaseAdapter的getView方法中,,用来获取整个View并返回。
下面就是其中一个例子:
 private class MyAdapter extends ArrayAdapter<Contact> {

  private int resource;
  private LayoutInflater inflater = null;
  private ArrayList<Contact> contacts;

  public MyAdapter(Context context, int resource,
    ArrayList<Contact> contacts) {
   super(context, resource);
   this.resource = resource;
   this.contacts = contacts;

   inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

   if (convertView == null)
    convertView = inflater.inflate(resource, null);

   Contact c = getItem(position);

   TextView text1 = (TextView) convertView
     .findViewById(android.R.id.text1);
   TextView text2 = (TextView) convertView
     .findViewById(android.R.id.text2);

   //首字符,分组的依据。
   text1.setText(c.firstLetterOfName());
   
   //详情。
   text2.setText(c.name + " " + c.getPhoneNumbers());

   return convertView;
  }
LayputInflater的用法有三种:
1:
LayoutInflater inflater = LayoutInflater.from(this);
View layout = inflater.inflate(R.layout.main, null);
2:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.main, null);
3:
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.main, null);
那LayoutInflater的inflate(int resource,ViewGroupr root,boolean attachToRoot)方法的三个参数的含义是什么呢?
resource:是需要加载的布局文件的ID,
root:如果第三个参数为true,那就是你实例化的view为root的子view
attachToRoot:自然解决
若只是单纯获得布局文件对其进行操作,可写成View layout = inflater.inflate(R.layout.main, null);的形式。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值