我发现这篇文章How to add a switch to android action bar?,这对我有用。但我不能得到它的事件。我正在使用appcompat,我使用了app命名空间for actionLayout和showAsAction,但是我无法处理它对onOptionsItemSelected方法的点击?我的应用程序在启动时崩溃了。如何处理它或这段代码有什么问题? 这是我的代码
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<item
android:id="@+id/myswitch"
android:title=""
app:showAsAction="always"
app:actionLayout="@layout/switch_layout"/>
switch_layout.xml
<?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" >
<Switch
android:id="@+id/switchForActionBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true" />
</RelativeLayout>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.your_menu, menu);
MenuItem menuItem= menu.findItem(R.id.myswitch);
Switch switcha = (Switch)menuItem.findViewById(R.id.switchForActionBar);
switcha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do anything here on check changed
}
});
return super.onCreateOptionsMenu(menu);
}
和
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.myswitch) {
//do something
}
return super.onOptionsItemSelected(item);
}
非常感谢任何帮助。提前谢谢。
答案 0 :(得分:14)
我发现了我的错误。我必须使用
View view = MenuItemCompat.getActionView(menuItem);
onCreateOptionsMenu中的额外行找出切换按钮 。这是我的完整方法
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.myswitch);
View view = MenuItemCompat.getActionView(menuItem);
Switch switcha = (Switch) view.findViewById(R.id.switchForActionBar);
switcha.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// do anything here on check changed
}
});
return super.onCreateOptionsMenu(menu);
}