java - 我不明白Android AutoCompleteTextView ArrayAdapter的构造函数

标签 java android android-arrayadapter

我想在android中使用AutoCompleteTextView并阅读有关它的官方developer.android文档。

有一个代码 fragment ,如下所示:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
             android.R.layout.simple_dropdown_item_1line, COUNTRIES);
     AutoCompleteTextView textView = (AutoCompleteTextView)
             findViewById(R.id.countries_list);
     textView.setAdapter(adapter);
 }

 private static final String[] COUNTRIES = new String[] {
     "Belgium", "France", "Italy", "Germany", "Spain"
 };

我不明白ArrayAdapter构造函数中的第二个参数(android.R.layout.simple_dropdown_item_1line)是什么意思,它来自哪里?

这是 Android 提供的布局还是我必须用自己创建的布局替换此布局以及在这种情况下如何定义此布局文件?

具体我的代码看起来像 xml:

<AutoCompleteTextView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

java:

AutoCompleteTextView search =(AutoCompleteTextView) findViewById(R.id.search);
String[] vocabs = new String[1001];
//fill the String array
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line ,vocabs);
search.setAdapter(adapter);

最佳答案

它们使用 3 个参数调用 ArrayAdapter 的构造函数 ( documentation ): ArrayAdapter(Context context, int resources, T[] objects)

资源R.layout.simple_dropdown_item_1line只是下拉菜单的默认android框架布局之一。请参阅here其他默认布局的列表。

编辑回答你的第二个问题:

您可以使用默认的 Android 布局(您提供的示例应该可以使用)或您定义的自定义布局。如果是最后一种情况,那么只需为此布局创建一个 xml 布局:

layouts/dropdown_custom_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">
    <TextView
        android:id="@+id/vocab_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:text="vocab"/>
</LinearLayout>

然后您可以使用 ArrayAdapter 构造函数 ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) 指向您的自定义布局和您想要填充词汇的 TextView:

ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.dropdown_custom_view, R.id.vocab_text ,vocabs);
search.setAdapter(adapter);

还要检查您是否正确填充了 vocabs 数组。

关于java - 我不明白Android AutoCompleteTextView ArrayAdapter的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46112344/

相关文章:

java - "Copy"Neo4j 中的弧线

java - 如何使用私有(private)构造函数运行最终类中的方法?

android - 开始另一个 Activity 时取消所有计时器

android - 更改数组适配器中列表项的文本颜色

android - 未使用 PullToRefresh 库调用自定义适配器 getView()

android - ListView 数据未显示在 fragment 中

java - 为什么我的价格字符串没有显示在应用程序中

java - 我的 DamageReductionAmmounts 导致 Minecraft 崩溃

java - 调用接口(interface)时使用匿名类

android - 最终的 .apk 是否包含未引用/使用的图像?