我有两个相似的按钮
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/sync_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sync"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
添加为菜单项
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/toggle_item"
android:title=""
app:showAsAction="always"
app:actionLayout="@layout/switch_button"
/>
<item
android:id="@+id/sync_item"
android:title=""
app:showAsAction="always"
app:actionLayout="@layout/sync"
/>
</menu>
我在onCreateOptionsMenu中使用inflate方法将项目添加到菜单中。
getMenuInflater().inflate(R.menu.menu_main, menu);
一切看起来都很好,但是当我点击应用程序时,因为onOptionsItemSelected(MenuItem item)从未被调用,所以没有任何反应。
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Integer test = item.getItemId();
switch (item.getItemId()) {
case R.id.toggle_item:
...
case R.id.sync_item:
...
return super.onOptionsItemSelected(item);
}
添加工具栏
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);