我想在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/