gpt4 book ai didi

android - 清除导航上的 Searchview 文本。

转载 作者:行者123 更新时间:2023-12-05 07:55:34 24 4
gpt4 key购买 nike

我有一个包含两个子 fragment 的 Activity TimelineMilestones。这两个 fragment 都包含由自定义 Cursor 适配器填充的 ListView

这是一个图形表示:enter image description here

现在,当我在 TIMELINE 上并打开搜索 View 时,我输入的内容都很好,我得到了想要的结果。但是,当我使用 searchview 中的一些文本 从时间轴导航到里程碑时,搜索 View 不会被清除,因此我也在里程碑页面上根据我在时间轴中提供的参数获得过滤结果。

我正在使用 AppCompact 库来开发我的 ActionBar。那里的选项卡不是 ActionBar 选项卡,而是简单的 SlidingTabLayout

到目前为止我已经尝试过使用

getActivity().supportInvalidateOptionsMenu();在两个 fragment 的 onResume() 中,不起作用。

我已经尝试过 searchView.setQuery("",false) - 不起作用并且随机给我一个 NPE。

那么我在这里想念什么?

最佳答案

您可以看一下我的示例,我在其中展示了如何控制 fragment 之间的 searchView。

首先。您需要创建 BaseFragment,它与 appBarLayout 的 Activity 上下文一起工作。

open class BaseFragment: Fragment() {
lateinit var rootActivity: MainActivity
lateinit var appBarLayout: AppBarLayout
lateinit var searchView: androidx.appcompat.widget.SearchView

override fun onAttach(context: Context) {
super.onAttach(context)

this.rootActivity = context as MainActivity
appBarLayout = rootActivity.findViewById(R.id.app_bar_layout)
searchView = rootActivity.findViewById(R.id.search_input)
}

override fun onResume() {
super.onResume()

resetAppBarLayout()
}

private fun resetAppBarLayout() {
appBarLayout.elevation = 14f
}

fun setupSearch(query: String) {
searchView.visibility = View.VISIBLE
searchView.clearFocus()
when(query.isNotEmpty()) {
true -> {
searchView.setQuery(query, true)
searchView.isIconified = false
}
false -> {
searchView.isIconified = true
searchView.isIconified = true
}
}
}

fun hideSearchKeyboard() {
context?.let {
KeyboardHelper.hideSearchKeyboard(it, searchView.findViewById(R.id.search_src_text))
}
}

fun hideSearch() {
searchView.visibility = View.GONE
searchView.clearFocus()
}
}

其次。从 BaseFragment 继承您的 fragment ,覆盖 onResume() 方法并通过调用 BaseFragment 的方法控制 fragment 中的 searchView。像这样。

class FragmentA : BaseFragment() {
private var searchQuery = ""

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment, container, false)
val textView: TextView = root.findViewById(R.id.textView)
textView.text = "Fragment A"
return root
}

override fun onResume() {
super.onResume()

setupSearch()
}

private fun setupSearch() {
searchView.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextChange(newText: String?): Boolean {
when(newText.isNullOrEmpty()) {
true -> searchQuery = ""
false -> searchQuery = newText
}
return true
}

override fun onQueryTextSubmit(query: String?): Boolean {
hideSearchKeyboard()
return true
}
})

super.setupSearch(searchQuery)
}
}

您可以在此处找到完整示例 https://github.com/yellow-cap/android-manage-searchview

关于android - 清除导航上的 Searchview 文本。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29625618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com