1

アクションバーのアクションとして表示されるメニュー内にスイッチがあります。checked プロパティを 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>
4

1 に答える 1

2

R.layout.switch_layout

レイアウト ファイルでは、チェックされた値の切り替えが既に true になっています。

android:checked="true"

したがって、その値を true に設定すると、そのチェック済み変更リスナーは呼び出されません。

あなたが私の主張を理解してくれることを願っています。

于 2015-08-20T23:16:50.340 に答える