将工具栏中搜索栏的背景更改为白色?

时间:2017-03-28 23:10:51

标签: android android-layout android-activity android-styles android-search

我在工具栏中实现了一个搜索栏,目前看起来像这样:

但是我想用阴影将背景更改为白色,这样它看起来更像是这样(取自Material Design指南):

我该怎么做?

以下是我对SearchView的实现:

menu_main.xml

<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

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

</menu>

MainActivity.java

public abstract class MainActivity extends AppCompatActivity {

    protected Toolbar toolbar;

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);

        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(final Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        final MenuItem searchItem = menu.findItem(R.id.action_search);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchActivity.class)));
        searchView.setQueryHint("Search");

        MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                setMenuItemVisibility(menu, searchItem, false);
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                supportInvalidateOptionsMenu();
                return true;
            }
        });

        return true;
    }

    private void setMenuItemVisibility(Menu menu, MenuItem searchItem, boolean isVisible) {
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            Log.d(TAG, item.toString());
            if (item != searchItem) {
                item.setVisible(isVisible);
            }
        }
    }
}

如何设置SearchView的样式以更改背景颜色?

0 个答案:

没有答案