[尝试关闭搜索视图时出现奇怪的行为

问题描述 投票:1回答:1

我创建了一个带有搜索图标的工具栏,该工具栏可在clic上启动searchview。但是,当用户在手机上按回去以关闭搜索视图时,我尝试添加一个setOnQueryTextFocusChangeListener,但是该图标显示在左侧,并且工具栏的后退图标始终存在。

enter image description here


这是我的工具栏的xml代码:

<com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBarLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/white"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/topAppBar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:navigationIcon="@drawable/ic_menu"
            app:title="Notes" />
    </com.google.android.material.appbar.AppBarLayout>

使用菜单:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/search"
        android:icon="@drawable/ic_search"
        android:title="Search"
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView" />

</menu>

我的活动:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        topAppBar = findViewById(R.id.topAppBar);
        setSupportActionBar(topAppBar);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.top_app_bar, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final SearchView searchView = (SearchView) item.getActionView();

        if (item.getItemId() == R.id.search) {

            searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        searchView.setIconified(true);
                    }
                }
            });
        }

        return super.onOptionsItemSelected(item);
    }

PS:此搜索视图存在很多问题,您是否有更好的方法在工具栏中添加搜索机制?

java android android-studio menu searchbar
1个回答
0
投票

我通过添加解决问题:

@Override
    public void onBackPressed() {
        if (searchView != null && !searchView.isIconified())
            searchView.setIconified(true);
        super.onBackPressed();
    }
© www.soinside.com 2019 - 2024. All rights reserved.