Android: Using Switch Preference pre API level 14

后端 未结 5 1655
有刺的猬
有刺的猬 2020-12-13 19:04

Pre-API Level 14 there is no switch preference. If I use preferences.xml to create my preference screen is there some way to distinguish between the API levels? So having a

5条回答
  •  执念已碎
    2020-12-13 20:10

    There is a workaround which i'm not sure how full it is, by wrapping which view to use in the CheckBoxPreference (might miss some functions, but in general use, it works) .

    The workaround will use the CheckBoxPreference for pre-API-14 and the SwitchPreference for API 14 and above.

    Here's the code:

    public class SwitchPreference extends CheckBoxPreference
      {
      android.preference.SwitchPreference _switchPreference =null;
    
      public SwitchPreference(final Context context)
        {
        super(context);
        if(VERSION.SDK_INT>=VERSION_CODES.ICE_CREAM_SANDWICH)
          _switchPreference=new android.preference.SwitchPreference(context);
        }
    
      public SwitchPreference(final Context context,final AttributeSet attrs)
        {
        super(context,attrs);
        if(VERSION.SDK_INT>=VERSION_CODES.ICE_CREAM_SANDWICH)
          _switchPreference=new android.preference.SwitchPreference(context,attrs);
        }
    
      public SwitchPreference(final Context context,final AttributeSet attrs,final int defStyle)
        {
        super(context,attrs,defStyle);
        if(VERSION.SDK_INT>=VERSION_CODES.ICE_CREAM_SANDWICH)
          _switchPreference=new android.preference.SwitchPreference(context,attrs,defStyle);
        }
    
      @Override
      protected View onCreateView(final ViewGroup parent)
        {
        final View view;
        if(VERSION.SDK_INT>=VERSION_CODES.ICE_CREAM_SANDWICH)
          {
          view=_switchPreference.getView(null,parent);
          // set as checked the view and the view's children, each in case it extend from Checkable
          ViewUtil.setChecked(view,isChecked());
          // set as non-clickable the view and the view's children
          ViewUtil.setClickable(view,false);
          }
        else view=super.onCreateView(parent);
        return view;
        }
    

提交回复
热议问题