设置Android Preference相关样式

这段时间在做一个Android小项目,系统设置中用到了Preference(偏好),使用google默认的PreferenceActiivty实现了该功能,但都是默认的背景和字体。怎么才改变它们的样式呢?PreferenceActivity继承ListActivity,所以本质上它是列表,所以可以通过得到它的ListView来设置背景或其它样式,如:

  1. getListView().setBackgroundColor(Color.BLUE);
复制代码

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

  1. getListView().setCacheColorHint(Color.TRANSPARENT);
复制代码

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

  1. package com.rlht.enforce.widget;
  2. import android.content.Context;
  3. import android.graphics.Color;
  4. import android.graphics.Typeface;
  5. import android.preference.PreferenceCategory;
  6. import android.util.AttributeSet;
  7. import android.view.View;
  8. import android.widget.TextView;
  9. /**
  10. * 自定义设置Preference的category。google默认的Category无法提供修改样式的接口
  11. * @author Zhuhanshan
  12. *
  13. */
  14. public class MyPreferenceCategory extends PreferenceCategory{
  15.         public MyPreferenceCategory(Context context, AttributeSet attrs) {
  16.                 super(context, attrs);
  17.         }
  18.         @Override
  19.         protected void onBindView(View view) {
  20.                 super.onBindView(view);
  21.                 view.setBackgroundColor(Color.GRAY);
  22.                 if(view instanceof TextView){
  23.                         TextView tv = (TextView) view;
  24.                         tv.setTextSize(18);
  25.                 }
  26.         }
  27. }
复制代码

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

  1. <com.rlht.enforce.widget.MyPreferenceCategory android:title="@string/base_setting">
  2.                 <EditTextPreference android:key="username"
  3.                         android:defaultValue="@null"
  4.                         android:title="@string/username"/>
  5.                 <EditTextPreference android:key="password"
  6.                         android:defaultValue="@null" 
  7.                         android:title="@string/password" />
  8.         </com.rlht.enforce.widget.MyPreferenceCategory>
复制代码

搞定....

原文地址:https://www.cnblogs.com/kevincode/p/3838566.html