默认情况下不会选中“切换”按钮

时间:2017-09-10 09:33:33

标签: android android-layout button menu android-actionbar

我已切换操作栏并且工作正常但我希望默认情况下通过设置XML android:checked="true"以及代码

进行检查
Switch switchButton=new Switch(getActivity());
        switchButton.setEnabled(true);

当应用程序启动时,默认情况下始终未选中。这是我的开关代码

public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    inflater.inflate(R.menu.switch_menu,menu);
    MenuItem switchItem=menu.findItem(R.id.toggle_loc);
    Switch switchButton=new Switch(getActivity());
    switchButton.setEnabled(true);
    MenuItemCompat.setActionView(switchItem,switchButton);

    switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                Log.d(TAG,"Switch Button Is Checked");
            }
            else {
                Log.d(TAG,"Switch Button Is UnChecked");
            }

        }
    });

R.menu.switch_menu

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/toggle_loc"
        android:title=""
        android:visible="true"
        app:actionLayout="@layout/switch_button"
        app:showAsAction="ifRoom">

    </item>

</menu>

布局/ switch_button&#34;

<?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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/Switch_Location"
        android:enabled="true"
        android:checked="true"

        />


</RelativeLayout>

默认情况下,请帮助我检查此开关。

1 个答案:

答案 0 :(得分:1)

使用

switchButton.setChecked(true);

你也这样做错了:

Switch switchButton=new Switch(getActivity());
而你应该做

Switch switchButton = (Switch) switchItem.getActionView().findViewById(R.id.Switch_Location);

所以看起来应该是这样的:

Switch switchButton = (Switch) switchItem.getActionView().findViewById(R.id.Switch_Location);
switchButton.setChecked(true);