`
weicaijin8
  • 浏览: 32695 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

修改设置Android Preference相关样式

阅读更多
使用google默认的PreferenceActiivty实现了该功能,但都是默认的背景和字体。怎么才改变它们的样式呢?PreferenceActivity继承ListActivity,所以本质上它是列表,所以可以通过得到它的ListView来设置背景或其它样式,如:

    getListView().setBackgroundColor(Color.BLUE);

复制代码
背景颜色是变了,当时当你滚动这个列表项时候,是不是会发现后面好像还有黑色背景。那怎么去掉这个黑色背景呢?只需要改变它的缓存色为透明即可,如:

    getListView().setCacheColorHint(Color.TRANSPARENT);

复制代码
这样就解决了滚动黑屏的问题了。其实还有一个地方的样式不知道怎么修改。就是PreferenceCategory(偏好分类)的样式怎么修改呢?我参考了其它人的一些观点,发现都没有生效。最后看了PreferenceCategory的源码,发现了该类的注释:Used to group {@link Preference} objects * and provide a disabled title above the group.这说明这上面标题是disabled的。那怎么才可以修改呢?最后经过测试,发现自定义一个PrefereceCategory可以达到自己的要求,java代码如下:

    package com.rlht.enforce.widget;

    import android.content.Context;
    import android.graphics.Color;
    import android.graphics.Typeface;
    import android.preference.PreferenceCategory;
    import android.util.AttributeSet;
    import android.view.View;
    import android.widget.TextView;
    /**
    * 自定义设置Preference的category。google默认的Category无法提供修改样式的接口
    * @author Zhuhanshan
    *
    */
    public class MyPreferenceCategory extends PreferenceCategory{

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

            @Override
            protected void onBindView(View view) {
                    super.onBindView(view);
                    view.setBackgroundColor(Color.GRAY);
                    if(view instanceof TextView){
                            TextView tv = (TextView) view;
                            tv.setTextSize(18);
                    }
            }

    }

复制代码
然后在peference.xml中使用这个自定义组件即可,xml如下:

    <com.rlht.enforce.widget.MyPreferenceCategory android:title="@string/base_setting">
                    <EditTextPreference android:key="username"
                            android:defaultValue="@null"
                            android:title="@string/username"/>
                    <EditTextPreference android:key="password"
                            android:defaultValue="@null"
                            android:title="@string/password" />
            </com.rlht.enforce.widget.MyPreferenceCategory>

复制代码
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics