自定义一个SwitchPreference,SwitchPreference使用自定义布局,要求switch在最左侧,中间是title、结束是icon
时间: 2024-01-24 07:16:56 浏览: 34
首先,我们需要自定义一个布局文件,命名为 custom_switch_preference.xml,代码如下:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Switch
android:id="@+id/switch_widget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentStart="true"
android:layout_marginStart="16dp" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="@+id/switch_widget"
android:textAppearance="?attr/textAppearanceListItem"
android:textColor="?attr/textColorSecondary"
android:textSize="16sp" />
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:contentDescription="@string/icon_description"
android:src="@drawable/ic_settings" />
</RelativeLayout>
```
其中,我们使用了一个RelativeLayout作为根布局,里面包含一个Switch、一个TextView和一个ImageView。Switch在最左侧,TextView在中间,ImageView在最右侧。
接下来,我们需要自定义一个SwitchPreference类,代码如下:
```
public class CustomSwitchPreference extends SwitchPreference {
public CustomSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
setWidgetLayoutResource(R.layout.custom_switch_preference);
}
public CustomSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public CustomSwitchPreference(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.switchPreferenceStyle);
}
public CustomSwitchPreference(Context context) {
this(context, null);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
TextView titleView = view.findViewById(R.id.title);
ImageView iconView = view.findViewById(R.id.icon);
if (titleView != null) {
titleView.setText(getTitle());
}
if (iconView != null) {
iconView.setImageDrawable(getIcon());
}
}
}
```
其中,我们重写了四个构造方法,并在构造方法中调用了setWidgetLayoutResource()方法,指定了自定义布局文件。同时,我们还重写了onBindView()方法,获取自定义布局中的TextView和ImageView,并设置对应的文本和图标。
最后,在我们的PreferenceScreen中使用CustomSwitchPreference即可,代码如下:
```
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<com.example.app.CustomSwitchPreference
android:key="example_switch_preference"
android:title="Example Switch Preference"
android:icon="@drawable/ic_settings"
android:defaultValue="true" />
</PreferenceScreen>
```
注意,我们在CustomSwitchPreference中并没有设置Switch的状态,这是因为SwitchPreference会自动根据SharedPreferences中的值来设置Switch的状态。如果需要在代码中手动设置Switch的状态,可以调用setChecked()方法。