Non è necessario creare un nuovo componente.
Prima di tutto, è necessario utilizzare CheckBoxPreference
anziché SwitchPreference per supportare API inferiori.
Utilizzando il widget esistente android.support.v7.widget.SwitchCompat
, creare un nuovo file di layout, ad esempio l_switch.xml
. Utilizzare il seguente codice:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.SwitchCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/checkbox" <!-- IMPORTANT -->
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:clickable="false" <!-- IMPORTANT -->
android:focusable="false" <!-- IMPORTANT -->
android:gravity="center" />
Poi, alla tua SwitchPreferenceCheckBoxPreference in PreferenceFragment
,
yourSwitch = findPreference("key_for_this_component");
yourSwitch.setWidgetLayoutResource(R.layout.l_switch);
o, al vostro CheckBoxPreference direttamente,
android:widgetLayout="@layout/l_switch"
Questo costringerà la CheckBoxPreference per utilizzare lo stile SwitchCompat
.
Ho modificato la mia risposta. Si prega di utilizzare la risposta modificata. – jyoon