将搜索视图小部件放在工具栏中的右上角

时间:2018-08-16 13:18:05

标签: android android-toolbar searchview android-search

我想将搜索小部件放在工具栏的右上角,然后按一下将其完全打开到左侧。但是如果搜索视图超出了屏幕。

有什么想法吗?

   <android.support.v7.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.SearchView
                android:layout_width="47dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                app:barrierDirection="left"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

            </android.support.v7.widget.SearchView>
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.Toolbar>

1 个答案:

答案 0 :(得分:0)

显示搜索图标+将其扩展到搜索编辑文本的最简单方法是使用菜单项:

<item android:id="@+id/search"
    android:title="@string/search_title"
    android:icon="@drawable/ic_search_white_24dp"
    app:showAsAction="collapseActionView|ifRoom"
    app:actionViewClass="android.support.v7.widget.SearchView" />

然后在onCreateOptionsMenu中执行您的逻辑

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.transcation_filter, menu);
        // Associate searchable configuration with the SearchView
        SearchManager searchManager =
                (SearchManager) getContext().getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =
                (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(
                searchManager.getSearchableInfo(getActivity().getComponentName()));

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                mViewModel.filter(newText);
                return false;
            }
        });
        super.onCreateOptionsMenu(menu, inflater);
    }

折叠式搜索看起来像

enter image description here

并展开

enter image description here