在Android Lollipop中扩展Preference类=丢失动画

Fer*_*gre 7 android android-preferences material-design android-5.0-lollipop

仅仅为了在Android Lollipop上扩展CheckBoxPreferenceSwitchPreference,小部件(复选框或开关)将不再具有动画.

我想扩展SwitchPreference以强制api <21使用SwitchCompat而不是他们使用的默认值(这显然是错误的).

我正在使用新的AppCompatPreferenceActivity,appcompat-v7:22.1.1但这似乎不会影响交换机.

问题是,只需扩展这些类,而不添加任何自定义布局或窗口小部件资源布局,动画就会消失.

我知道我可以编写两个我的preference.xml实例(在内部值-v21上)并且它可以工作......但我想知道为什么会发生这种情况,如果有人知道没有两个preference.xml的解决方案.

代码示例:

public class SwitchPreference extends android.preference.SwitchPreference {

    public SwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public SwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public SwitchPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SwitchPreference(Context context) {
        super(context);
    }
}
Run Code Online (Sandbox Code Playgroud)

对于CheckBoxPreference这个或相同,然后使用:

<com.my.package.SwitchPreference />

将使Lollipop设备中的动画消失.

-

我尝试了SwitchPreference另一件事(我能与CheckBoxPreference)是为了给使用默认ID的布局,但@android:id/switchWidget不公开,而@android:id/checkbox为.我也知道我可以使用a <CheckBoxPreference />并给出一个实际上是SwitchCompat的小部件布局,但我想避免这种情况(混淆名称).

小智 -1

公共类 SwitchPreference 扩展 android.preference.SwitchPreference {

public SwitchPreference(Context context) {
    this(context, null);
}

public SwitchPreference(Context context, AttributeSet attrs) {
    this(context, attrs, android.R.attr.checkBoxPreferenceStyle);
}

public SwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
    this(context, attrs, defStyleAttr, 0);
}

public SwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);

    try {
        Field canRecycleLayoutField = Preference.class.getDeclaredField("mCanRecycleLayout");
        canRecycleLayoutField.setAccessible(true);
        canRecycleLayoutField.setBoolean(this, true);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
Run Code Online (Sandbox Code Playgroud)