actionbar中添加searchview并监听期伸缩/打开的方法
首先在xml中设置actionviewclass
<item android:id="@+id/m1" android:title="setting" android:icon="@drawable/abc_ic_search_api_mtrl_alpha" android:showAsAction="always|collapseActionView" android:actionViewClass="android.widget.SearchView" />
然后在oncreateoptionmenu方法中获得menu实例,并设置监听
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.optionmenu, menu); MenuItem search = menu.findItem(R.id.m1); SearchView searchView = (SearchView) search.getActionView(); MenuItemCompat.setOnActionExpandListener(search, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionCollapse(MenuItem item) { // Do something when collapsed Toast.makeText(MainActivity.this, "hello expand", Toast.LENGTH_LONG).show(); return true; // Return true to collapse action view } @Override public boolean onMenuItemActionExpand(MenuItem item) { // Do something when expanded Toast.makeText(MainActivity.this, "hello expand", Toast.LENGTH_LONG).show(); return true; // Return true to expand action view } }); return true; }
注意添加监听的方式
-----人若无名,则可专心练剑