首先在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; }
注意添加监听的方式
时间: 2024-10-03 21:54:18