Custom SwitchPreference in Android

前端 未结 3 402
粉色の甜心
粉色の甜心 2020-12-03 11:49

How to set a custom style or other background selector drawable for the SwitchPreference widget in Android?

(Note: not the regular Switch

3条回答
  •  既然无缘
    2020-12-03 11:59

    You have to create a custom layout for the switch itself and you can apply it dynamically like.

    preference.setWidgetLayoutResource(R.layout.custom_switch);
    

    But I'll go into details and show you exactly how to achieve this.

    So, you define your preference in an xml file like preferences.xml

    
    
        
            
        
    
    

    Then read it in the onCreate() method inside your PreferenceActivty class:

        SwitchPreference pref = (SwitchPreference) findPreference(getString(R.string.SWITCH));
        //pref.setChecked(true); // You can check it already if needed to true or false or a value you have stored persistently
        pref.setWidgetLayoutResource(R.layout.custom_switch); // THIS IS THE KEY OF ALL THIS. HERE YOU SET A CUSTOM LAYOUT FOR THE WIDGET
        pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
    
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                // Here you can enable/disable whatever you need to
                return true;
            }
        });
    

    The custom_switch layout looks like this:

    
    
    

    And for the switch you'll have 2 selectors for the track and thumb properties. The drawables for these selectors can be generated with the Android Holo Color Generator, which was suggested by tasomaniac. In this case, all you have to do, is to copy the content of the generated drawable folders(only for the drawable-hdpi, drawable-mdpi, drawable-xhdpi, drawable-xxhdpi). But you can create custom views for each state you need.

    Here is how these selectors will look like: switch_track:

    
        
    
        
        
    
    
    

    switch_thumb:

    
         
    
         
         
         
         
    
    
    

    And that's pretty much it. This solution helped me out. If I omitted something, please let me know and I'll correct the issues.

提交回复
热议问题