【发布时间】:2015-08-20 21:54:23
【问题描述】:
我在菜单中有一个开关,它显示为操作栏上的操作。在我将选中的属性设置为 true 后,不会立即调用 onCheckedChangeListener。该开关确实显示在操作栏中,每次按下它都会调用checkedchangelistener。然而,它并没有在它应该被调用的时候被调用。这怎么可能?为什么不调用它?我该如何解决这个问题?
这里是onCreateMenuOptionsMenu:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "onCreateOptionsMenu()");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
serviceSwitch = (Switch) menu.findItem(R.id.Switch).getActionView().findViewById(R.id.switchid);
serviceSwitch.setOnCheckedChangeListener(mCheckedChangeListener);
serviceSwitch.setChecked(false);
//OnCheckedChange is not being called here. I have set a breakpoint at the method.
//I have also looked at the log - nothing.
//It is being called when I click the switch however.
return true;
}
private OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i(TAG, isChecked ? "true" : "false";
}
}
这里是xml:
R.menu.mainmenu
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:title=""
android:id="@+id/Switch"
android:actionLayout="@layout/switch_layout"
android:showAsAction="always"></item>
</menu>
R.layout.switch_layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Switch
android:id="@+id/switchid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:paddingRight="20dp"
android:paddingLeft="20dp"
android:textOff="Off"
android:textOn="On"
android:checked="true"/>
</RelativeLayout>
【问题讨论】:
-
我正在使用一个活动
-
uhh... 这不相关,并且活动未被弃用developer.android.com/reference/android/app/Activity.html
-
如果它已被弃用,则会出现“此类已弃用”。 developer.android.com/reference/android/support/v7/app/…
标签: android android-actionbar android-widget android-menu oncheckedchanged