我正在使用API 8开发应用程序。现在我正在尝试在菜单中添加3个项目,一个
我添加的项目是SearchView,我用app:actionViewClass="android.support.v7.widget.SearchView"
来支持API 8,
在onOptionsItemSelected(MenuItem item)
的我的MainActivity类中,我正在尝试处理searchView上的点击,但它已不再有效。
怎么解决这个问题?
menu.xml文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!--My SearchView--->
<item
android:id="@+id/menu_search"
android:orderInCategory="100"
android:title="@string/stringSearch"
app:actionViewClass="android.support.v7.widget.SearchView"
android:icon="@drawable/ic_magnify"
app:showAsAction="always"/>
<!--My Filter--->
<item
android:id="@+id/menu_filter"
android:orderInCategory="100"
android:icon="@drawable/ic_filter"
android:title="@string/StringFilter"
app:showAsAction="always" />
<!--Some menu--->
<item
android:id="@+id/menu_settings"
android:orderInCategory="100"
android:icon="@drawable/ic_dots"
android:title="@string/Settings"
app:showAsAction="always" />
</menu>
MainActivity.class
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
...
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
//I setup the searchView here
MenuItem searchItem = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
....
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
//This is click event on searchView but unfortunately not working
Toast.makeText(getApplicationContext(),"SearcView",Toast.LENGTH_LONG).show();
break;
case R.id.menu_settings:
Toast.makeText(getApplicationContext(),"Menu Settings",Toast.LENGTH_LONG).show();
break;
case R.id.menu_filter:
Toast.makeText(getApplicationContext(),"Menu Filter",Toast.LENGTH_LONG).show();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
所以,正如你在我的代码中看到的那样,当我点击菜单项时,我尝试触发一个吐司,一切正常但不是我的SearchView。
当我开始在searchView项目的菜单上添加app:actionViewClass="android.support.v7.widget.SearchView"
时会发生这种情况。
有人可以帮帮我吗?
非常感谢你!
答案 0 :(得分:1)
您希望在SearchView类上使用其中一个侦听器。 OnSearchClickListener看起来可能适合您。
编辑。这是一个代码示例:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnSearchClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Handle clicks
}
});
return super.onCreateOptionsMenu(menu);
}