创建始终折叠的材质设计SearchView

时间:2016-02-25 06:36:45

标签: android material-design searchview

我正在开发一个材质设计应用,我想实现一个需要折叠ToolBar和设置按钮的SearchView。我已成功实施了SearchView和设置菜单项。但问题是我希望SearchView在默认情况下被折叠。现在它仅在图标点击时折叠。

代码:

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
       return true;
    } 

 @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }
            else if (id == R.id.action_search) {
                final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
                SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
                searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

main.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="com.example.navigationdrawer.MainActivity" >


   <item android:id="@+id/action_search"
    android:title="Search"
    android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView" />

    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
</menu>

1 个答案:

答案 0 :(得分:0)

你必须使用

app:showAsAction="always|collapseActionView"

如果您希望它始终显示,但可以按照action views trainingProviding Search with SearchView video

中的说明展开