创建您自己的自定义适配器时 getView() 方法如何工作? [英] How does the getView() method work when creating your own custom adapter?

查看:32
本文介绍了创建您自己的自定义适配器时 getView() 方法如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是:

  1. LayoutInflater 的具体功能是什么?
  2. 为什么我读过的所有文章都会先检查 convertview 是否为 null?为 null 时是什么意思,不为 null 时是什么意思?
  3. 此方法接受的父参数是什么?

解决方案

1:LayoutInflater 获取您的布局 XML 文件并从其内容创建不同的视图对象.

2:适配器是为重用视图而构建的,当视图滚动到不再可见时,它可以用于出现的新视图之一.这个重用的视图是 convertView.如果为null,则表示没有回收的View,我们必须创建一个新的,否则我们应该使用它来避免创建一个新的.

3:提供了 parent 以便您可以将视图扩展为适当的布局参数.

所有这些都可以用来有效地创建将出现在您的列表中的视图(或其他需要适配器的视图):

public View getView(int position, @Nullable View convertView, ViewGroup parent){if (convertView == null) {//我们必须创建一个视图:convertView = inflater.inflate(R.layout.my_list_item, parent, false);}//这里我们可以对convertView做一些修改,比如在TextView上设置一个文本//或 ImageView 上的图像.返回转换视图;}

注意 LayoutInflater 的使用,parent 可以用作它的参数,以及如何重用 convertView.>

My questions are:

  1. What is exactly the function of the LayoutInflater?
  2. Why do all the articles that I've read check if convertview is null or not first? What does it mean when it is null and what does it mean when it isn't?
  3. What is the parent parameter that this method accepts?

解决方案

1: The LayoutInflater takes your layout XML-files and creates different View-objects from its contents.

2: The adapters are built to reuse Views, when a View is scrolled so that is no longer visible, it can be used for one of the new Views appearing. This reused View is the convertView. If this is null it means that there is no recycled View and we have to create a new one, otherwise we should use it to avoid creating a new.

3: The parent is provided so you can inflate your view into that for proper layout parameters.

All these together can be used to effectively create the view that will appear in your list (or other view that takes an adapter):

public View getView(int position, @Nullable View convertView, ViewGroup parent){
    if (convertView == null) {
        //We must create a View:
        convertView = inflater.inflate(R.layout.my_list_item, parent, false);
    }
    //Here we can do changes to the convertView, such as set a text on a TextView 
    //or an image on an ImageView.
    return convertView;
}

Notice the use of the LayoutInflater, that parent can be used as an argument for it, and how convertView is reused.

这篇关于创建您自己的自定义适配器时 getView() 方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆