ArrayAapter Class have some constructors: enter image description here

什么时候使用构造函数1和2?因为我们在这些构造函数中根本没有像输入数组或列表这样的数据 struct .如果可能,请举例说明.谢谢

推荐答案

这两个构造函数:

public ArrayAdapter (Context context, 
                int resource)


public ArrayAdapter (Context context, 
                int resource, 
                int textViewResourceId)

当您想要创建一个ArrayAdapter,但在创建它的时候没有数据时,可以使用.您可以稍后使用Add()、Insert()等方法添加数据.它们实际上在内部调用其他构造函数,并将空集合作为参数:

public ArrayAdapter(@NonNull Context context, @LayoutRes int resource) {
    this(context, resource, 0, new ArrayList<>());
}

public ArrayAdapter(@NonNull Context context, @LayoutRes int resource,
        @IdRes int textViewResourceId) {
    this(context, resource, textViewResourceId, new ArrayList<>());
}

例如,您可能希望在活动的onCreate()方法中为ListView创建一个ArrayAdapter,但填充ListView的数据是稍后从网络请求中获取的.在这种情况下,您可以使用第一个或第二个构造函数来创建ArrayAdapter,然后在网络请求完成后向其中添加数据.

以下是一些有用的链接:

https://developer.android.com/develop/ui/views/layout/declaring-layout#AdapterViews

https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/widget/ArrayAdapter.javae

[编辑] 如果使用第一个构造函数,则文本视图资源将为0,从源代码(上面的链接)可以了解到,在这种情况下,整个资源都被视为TextView:

    if (mFieldId == 0) {
            //  If no custom field is assigned, assume the whole resource is a TextView
            text = (TextView) view;
        } else {

Java相关问答推荐

查找最大子数组的和

我无法将附件发送到NetBeans之外

名称冲突具有相同的擦除

用户填充的数组列表永不结束循环

Java中将文本拆分为数字或十进制数字和字符串

搜索列表返回多个频道

如何为JavaFX Spring Boot应用程序制作Windows/MacOS/Linux安装程序

为什么有两种实现来检索数组类的组件类型?

基于配置switch 的@Controller的条件摄取

有谁能帮我修一下这个吗?使输出变得更加整洁

在使用具有不同成本的谓词调用allMatch之前对Java流进行排序会带来什么好处吗?

将java.util.Date(01.01.0001)转换为java.time.LocalDate将返回29.12.0000

为什么项目名称出现在我的GET请求中?

用于Java的Visual Studio代码完成不起作用

Win32函数的JNA绑定DwmGetColorizationColor返回E_INVALIDARG错误

Java KeyListener不工作或被添加

根据应用程序 Select 的语言检索数据

设置背景时缺少Android编辑文本下划线

从 Java 17 切换回 Java 8 后出现的问题

JAVA 正则表达式识别字符串string或字符串内的字符char