Android Preference修改点击条目的背景色

很多朋友在用Preference时,都觉得这个控件好用,但是很多的东西不能自己定制,比如字体大小,背景色,点击背景色等等,大家都知道这个控件是放在framework中的,总不能为了一个小需求就去改动framework的代码吧,本文就以修改点击背景色为例,提供一种在不改动framework的前提下定制自己风格的Preference的思路,首先,我们先来看看Preference的源码,
在路径platform_frameworks_base/core/java/android/preference/Preference.java下,

    /**
     * Creates the View to be shown for this Preference in the
     * {@link PreferenceActivity}. The default behavior is to inflate the main
     * layout of this Preference (see {@link #setLayoutResource(int)}. If
     * changing this behavior, please specify a {@link ViewGroup} with ID
     * {@link android.R.id#widget_frame}.
     * <p>
     * Make sure to call through to the superclass's implementation.
     *
     * @param parent The parent that this View will eventually be attached to.
     * @return The View that displays this Preference.
     * @see #onBindView(View)
     */
    @CallSuper
    protected View onCreateView(ViewGroup parent) {
        final LayoutInflater layoutInflater =
                (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        final View layout = layoutInflater.inflate(mLayoutResId, parent, false);

        final ViewGroup widgetFrame = (ViewGroup) layout
                .findViewById(com.android.internal.R.id.widget_frame);
        if (widgetFrame != null) {
            if (mWidgetLayoutResId != 0) {
                layoutInflater.inflate(mWidgetLayoutResId, widgetFrame);
            } else {
                widgetFrame.setVisibility(View.GONE);
            }
        }
        return layout;
    }

Preference的onCreateView方法里加载了一个mLayoutResId的布局,而这个布局变量定义在

    private int mLayoutResId = com.android.internal.R.layout.preference;

如果没有写死,而是用一个变量代表布局,那就说明必定对外提供了修改这个成员变量的方法,

    public void setLayoutResource(@LayoutRes int layoutResId) {
        if (layoutResId != mLayoutResId) {
            // Layout changed
            mRecycleEnabled = false;
        }

        mLayoutResId = layoutResId;
    }

通过这个方法可以设置自己的Preference布局,那么现在就可以总结一下步骤了,
第一步,重写一个类继承Preference,重写构造方法等一些方法。
第二步,仿照Preference的布局重写一套布局,在根布局里修改background属性为自己的selector。
第三步,在重写的Preference的构造函数里调用setLayoutResource设置自己的自定义布局。
第四步,将原本的Preference替换为自己的布局。

这样就可以定制自己的Preference了,什么字体什么颜色都可以按照自己的意愿在自己的布局修改。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值