我正在开发一个 Android 应用程序,它有一个抽屉导航、MainActivity 和六个 fragment 。每个抽屉导航项都会打开一个不同的 fragment 。 在 MainActivity 上,我包含了一个 searchview 小部件以将其用作搜索框:
主要 Activity :
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
// Retrieve the SearchView and plug it into SearchManager
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
菜单.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".HomeActivity">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</menu>
主页 fragment
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
Log.d("SEARCH", "pulsado search" );
return false;
default:
break;
}
return false;
}
它现在正在工作,我的意思是,当单击搜索图标时,会显示编辑文本。 如何让插入到此编辑文本中的文本与其一起使用?
最佳答案
我认为您正在查看下面的代码
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
最佳方法。
Please use interfacing mechanism for the fragments.Based on current fragment shown to user call callback method to notify fragment that search text changed. sample link
简单的方法。
Provide one public method all the fragments.Based on current fragment shown to user call method to notify fragment that search text changed.
最差方法。
use "getActivity" inside all the fragments then "findViewById", and use "setOnQueryTextListener". Make sure your having proper reference.
关于android - 从 fragment 中的 searchview 小部件获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54234865/