Android 自定义SwitchPreference

文章介绍了如何为AndroidSwitchPreference添加自定义背景、内外边距、颜色和字体,通过重写`onBindViewHolder`方法实现。展示了完整代码和使用示例。
摘要由CSDN通过智能技术生成

1. 为SwitchPreference 添加背景:custom_preference_background.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle" >
            <gradient android:startColor="@color/white" android:endColor="@color/white" android:angle="90"/>
            <corners android:radius="8dp"/>
        </shape>
    </item>
</selector>

2. 自定义 CustomSwitchPreference 继承自 witchPreference

public class CustomSwitchPreference extends SwitchPreference {

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

    public CustomSwitchPreference(Context context) {
        super(context);
    }

//
....
//
}

3. 重载  onBindViewHolder, 实现自定义的效果, 如:设置背景、添加外边距、设置内边距、修改文字的颜色和字体等等:

    @Override
    public void onBindViewHolder(PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);
    //设置背景

     
    
   holder.itemView.setBackgroundResource(R.drawable.custom_preference_background);
        
    //设置内边距
    holder.itemView.setPadding(
                DensityUtils.dp2px(getContext(),20),
                DensityUtils.dp2px(getContext(),2),
                DensityUtils.dp2px(getContext(),20),
                DensityUtils.dp2px(getContext(),2));

          //设置外边距
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)   holder.itemView.getLayoutParams();
        int textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 18, getContext().getResources().getDisplayMetrics());
        params.topMargin = DensityUtils.dp2px(getContext(),5);
        params.bottomMargin = DensityUtils.dp2px(getContext(),5);
        params.leftMargin = DensityUtils.dp2px(getContext(),20);
        params.rightMargin = DensityUtils.dp2px(getContext(),20);
        holder.itemView.setLayoutParams(params);

        TextView titleView = holder.itemView.findViewById(android.R.id.title);
        titleView.setTextColor(Color.BLACK); // 这里设置为红色,你可以根据需要设置其他颜色
        TextView summaryView = holder.itemView.findViewById(android.R.id.summary);
        summaryView.setTextColor(Color.BLACK); // 设置为黑色
    }

完整代码如下:

public class CustomSwitchPreference extends SwitchPreference {

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

    public CustomSwitchPreference(Context context) {
        super(context);
    }

    @Override
    public void onBindViewHolder(PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);
        holder.itemView.setBackgroundResource(R.drawable.custom_preference_background);
        holder.itemView.setPadding(
                DensityUtils.dp2px(getContext(),20),
                DensityUtils.dp2px(getContext(),2),
                DensityUtils.dp2px(getContext(),20),
                DensityUtils.dp2px(getContext(),2));

        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)   holder.itemView.getLayoutParams();
        int textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, 18, getContext().getResources().getDisplayMetrics());
        params.topMargin = DensityUtils.dp2px(getContext(),5);
        params.bottomMargin = DensityUtils.dp2px(getContext(),5);
        params.leftMargin = DensityUtils.dp2px(getContext(),20);
        params.rightMargin = DensityUtils.dp2px(getContext(),20);
        holder.itemView.setLayoutParams(params);

        TextView titleView = holder.itemView.findViewById(android.R.id.title);
        titleView.setTextColor(Color.BLACK); // 这里设置为红色,你可以根据需要设置其他颜色
        TextView summaryView = holder.itemView.findViewById(android.R.id.summary);
        summaryView.setTextColor(Color.BLACK); // 设置为蓝色
    }
}

用法:

    <com.tetras.sensechat.wedgit.CustomSwitchPreference
        app:defaultValue="true"
        app:iconSpaceReserved="false"
        app:key="key_continuous_switch"
        app:title="@string/text_continuous_switch" />

效果如图:

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要自定义一个布局文件,命名为 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()方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值