【问题标题】:Switch button is not checked by default切换按钮默认不勾选
【发布时间】:2017-09-10 09:33:32
【问题描述】:

我在操作栏中有开关,它工作正常,但我想通过在 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"

<?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>

请帮我把这个开关设为默认选中。

【问题讨论】:

  • 你的theme里面有什么?
  • @Yupi 抱歉,我删除了该行,因为主题是空白的,所以没有效果
  • 下面的答案没有解决您的问题?

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


【解决方案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);

【讨论】:

  • 正如你在问题中看到的,我已经说过我尝试过这种方法但不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 2020-09-08
  • 1970-01-01
  • 2021-01-26
  • 2019-08-01
  • 2019-01-16
  • 1970-01-01
相关资源
最近更新 更多