This is about the animation for SwitchCompat widget in accepted answer.
I found that the problem is caused by a flag in Preference class, in Android 4.0-4.3, the flag is mHasSpecifiedLayout, in Android 4.4 the flag is mCanRecycleLayout.
When you set the widget using setWidgetLayoutResource, it will change this flag.
If you create a new customized preference class using different package name(except android.preference or com.android), it will also change this flag.
When mHasSpecifiedLayout is false or CanRecycleLayout is true, the animation will work, otherwise the animation does not work.
So you can set the widget layout using reflection instead of setWidgetLayoutResource() method, then the animation will not be broken.
Here is a snippet:
CheckBoxPreference switchPref = new CheckBoxPreference(getActivity());
try {
Field field = Preference.class.getDeclaredField("mWidgetLayoutResId");
field.setAccessible(true);
field.setInt(switchPref, R.layout.preference_switch_layout);
} catch (Exception e) {
switchPref.setWidgetLayoutResource(R.layout.preference_switch_layout);
}
switchPref.setKey(key);
switchPref.setTitle(titleRes);
switchPref.setSummary(summaryRes);
switchPref.setDefaultValue(defaultValue);