androidXP
androidXP

Reputation: 1719

Switch button is not checked by default

I have switch in action bar and its working fine but i wanted to be checked by default by setting in XML android:checked="true" and also in code by

Switch switchButton=new Switch(getActivity());
        switchButton.setEnabled(true);

When the app launched its always unchecked by default. Here is my Code for switch

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>

layout/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>

Please help me to make this switch checked by default.

Upvotes: 1

Views: 2862

Answers (1)

Sandip Fichadiya
Sandip Fichadiya

Reputation: 3480

use

switchButton.setChecked(true);

also you are doing this wrong like:

Switch switchButton=new Switch(getActivity());

instead you should do

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

so it should look like:

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

Upvotes: 2

Related Questions