Search code examples
androidandroid-layoutandroid-5.0-lollipopandroid-switch

Switch control is not working on Dialog in Android version 5.0


I have used below switch in my application.

<Switch
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text=""
        android:thumb="@drawable/toggle_button_color"
        android:textOff="@string/text_estimate"
        android:textOn="@string/text_accurate" 
        android:textColor="@color/white" />

In above switch I am using toggle_button_color.xml to change the thumb color to green and red when switch is on and off respectively.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false" android:drawable="@color/red"  />
    <item android:state_checked="true" android:drawable="@color/green"  />   
</selector>

If I add this switch to an activity layout and then its wokring perfectly as below image. enter image description here enter image description here

But if I add this switch on Dialog using m_dialog.setContentView(R.layout.mylayout); then switch looks like below. Note that here mylayout.xml is a layout file in which I have added switch.

enter image description here

For android version below 5.0 lollipop switch is working fine as I want. Note that for some reasons I am using Theme.Holo.Light in my application so I can't use SwitchCompat.

I know that a similar question has been asked here Switch crashes when clicked on Android 5.0.

And also it is reported here https://code.google.com/p/android-developer-preview/issues/detail?id=1704. I have also tried the work around which is mentioned in above link to add drawable image for thumb and track, but I don't understand why same switch is working on activity layout but not on Dialog.

Can anybody please help me out with this?


Solution

  • Thank you all for your response, but I solved it by my own. Earlier I was implementing the dialog using the Dialog class, which was causing the problems.

    Dialog mDialog= new Dialog(getActivity(),android.R.style.Theme_Dialog);
    mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    mDialog.setContentView(R.layout.mylayout);
    

    I have even tried changing the themes but it didn't help.

    Then I tried using DialogFragment, which solved the issue.

    public class MyDialog extends DialogFragment{
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        View v = inflater.inflate(R.layout.mylayout, container, false);
        return v;
        }
    }
    

    And from my Activity class I invoke this Dialog as below.

    MyDialog mDialog = new MyDialog();
    mDialog .show(getFragmentManager(), "Hello");