我找到了这篇文章 How to add a switch to android action bar?这对我有用。但我无法得到它的事件。我正在使用 appcompat,并且我将 app 命名空间用于 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);
}
非常感谢任何帮助。提前致谢。
最佳答案
我发现了我的错误。我必须使用
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);
}
关于android - 如何在 Android 操作栏开关中获取/设置操作事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32091709/