android - Switch button is not checked by default -
i have switch in action bar , working fine wanted checked default setting in xml android:checked="true"
, in code
switch switchbutton=new switch(getactivity()); switchbutton.setenabled(true);
when app launched unchecked default. here code 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 checked"); } else { log.d(tag,"switch button 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 me make switch checked default.
use
switchbutton.setchecked(true);
also doing wrong like:
switch switchbutton=new switch(getactivity());
instead should do
switch switchbutton = (switch) switchitem.getactionview().findviewbyid(r.id.switch_location);
so should like:
switch switchbutton = (switch) switchitem.getactionview().findviewbyid(r.id.switch_location); switchbutton.setchecked(true);
Comments
Post a Comment