android - 使 EditText 提供搜索结果
问题描述
我用 ImageButton 创建了以下 EditText:
通过使用以下代码:
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.12">
<EditText
android:id="@+id/txt_search"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="24dp"
android:layout_marginTop="24dp"
android:layout_marginRight="24dp"
android:layout_marginBottom="8dp"
android:paddingLeft="24dp"
android:textSize="14sp"
android:background="@drawable/et_rounded"
android:hint="Search for book or author"
android:textColorHint="@color/colorGray"
app:layout_constraintTop_toTopOf="parent"/>
<ImageButton
android:id="@+id/btn_search"
android:layout_width="48dp"
android:layout_height="match_parent"
android:layout_marginLeft="24dp"
android:layout_marginTop="24dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:layout_alignRight="@id/txt_search"
android:background="@android:color/transparent"
android:src="@drawable/ic_search_black_24dp"/>
</RelativeLayout>
我试图得到两件事:
1)是否有一个选项可以在键盘中添加一个搜索按钮,一旦我单击此按钮,它将搜索结果,就像我在某些网站中搜索时一样,例如:
2)有没有办法制作弹出菜单之类的东西,一旦我输入编辑文本,它会提供很少的搜索结果?
谢谢
解决方案
回答你的两个问题:
首先指定 inputType 和 ime 选项:
<AutoCompleteTextView
android:id="@+id/autocomplete"
android:imeOptions="actionSearch"
android:inputType="text" />
然后注册适配器:
// field
val adapter by lazy { ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
autocomplete.setAdapter(adapter)
autocomplete.doOnTextChanged { text, _, _, _ ->
// Call api to find search results for your text:
callApiFor(text.toString())
}
autocomplete.setOnEditorActionListener { textView, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
// call an API to find your results
searchResults(textView.text.toString())
return@setOnEditorActionListener true
}
false
}
}
收到数据后:
adapter.clear()
adapter.addAll(resultsList)
adapter.notifyDataSetChanged()
搜索建议链接: http ://suggestqueries.google.com/complete/search?client=firefox&q=some%20query
这里有一些文档(非官方,因为我找不到任何官方文档): https ://shreyaschand.com/blog/2013/01/03/google-autocomplete-api/
您将获得以下格式的结果:
[
"some query",
[
"some query",
"some query in sql",
"some query in mysql",
"some query in oracle",
"some_queryset",
"queryselectorall some",
"querylist some",
"query some information",
"query some data",
"query some questions"
]
]
与谷歌相同:
推荐阅读
- python - 来自随机样本的 Python 概率
- html - 我们如何创建覆盖 50% 高度的下划线文本?
- c# - ObjectMapper 不会递归地映射子实体
- django - Authlib vs OAuthlib:这些库是一样的吗?
- android - 在 Kotlin 中对 ArrayList 进行排序
- python - pip 无法正确解决子/孙依赖项
- spring-boot - 将杰克逊配置拆分为单独的属性
- android - 一个简单的应用意图打开设置帐户
- javascript - 打字稿:仅测试 Nan、null 和 undefined
- oracle - 如何将 Freeradius 与 Oracle 数据库 XE(18c) 集成?