Android开发:点击搜索图标后仅显示SearchView,隐藏Toolbar
解决Toolbar在搜索时未隐藏的问题
我明白你的需求:点击搜索图标进入搜索界面后,希望原来的Toolbar完全隐藏,只让SearchView顶在屏幕顶部显示。现在Toolbar还留在顶部的问题,咱们可以通过以下两步修改代码来解决:
第一步:点击搜索时立即隐藏Toolbar
在你的onOptionsItemSelected方法里,触发搜索事件的分支中,添加隐藏Toolbar的代码。这里分两种情况,根据你使用Toolbar的方式选择:
else if (id == R.id.search) { if (Connectivity.isConnected(MainActivity.this)) { // 情况1:如果你是把Toolbar作为ActionBar使用的 getSupportActionBar().hide(); // 情况2:如果你是直接实例化了Toolbar对象(比如private Toolbar toolbar;) // toolbar.setVisibility(View.GONE); Bundle bundle = new Bundle(); bundle.putString("type", "search"); SearchFragment searchFragment = new SearchFragment(); searchFragment.setArguments(bundle); FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction() .add(R.id.container, searchFragment, SearchFragment.class.getSimpleName()) .addToBackStack("SearchFragment") .commit(); overridePendingTransition(R.anim.enter_from_right, R.anim.exit_to_left); } else { Utils.showNoConnectionToast(MainActivity.this); } }
第二步:返回主界面时重新显示Toolbar
当你点击返回键从SearchFragment回到主界面时,需要让Toolbar重新显示。可以在MainActivity的onCreate方法里添加一个回退栈监听:
// 在MainActivity的onCreate方法中添加这段代码 getSupportFragmentManager().addOnBackStackChangedListener(() -> { // 检查回退栈是否为空,为空说明回到了主界面 if (getSupportFragmentManager().getBackStackEntryCount() == 0) { // 对应第一步的两种情况,选择其中一种 getSupportActionBar().show(); // toolbar.setVisibility(View.VISIBLE); } });
额外优化:让SearchView顶满顶部
为了让隐藏Toolbar后的SearchView完全占据顶部位置,记得在SearchFragment的布局文件里,让SearchView的顶部对齐父布局,不要留空隙。比如布局示例:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- SearchView顶在布局最上方 --> <androidx.appcompat.widget.SearchView android:id="@+id/search_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/your_toolbar_color"/> <!-- 搜索结果区域 --> <RecyclerView android:id="@+id/search_results_rv" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
这样修改后,点击搜索图标时Toolbar会立刻隐藏,SearchView顶在屏幕最上方;返回主界面时Toolbar又会重新出现,完全符合你的需求。
内容的提问来源于stack exchange,提问作者pallavi richhariya
相关产品推荐
相关产品推荐

