更改PreferenceActivity文本颜色

7

我想将我的Android应用程序的偏好设置屏幕外观更改为深色文本颜色。我该如何做?(我已经将背景更改为白色)

2个回答

15

我假设您使用一个继承了PreferenceActivity的Activity。 您可以使用setTheme方法在您的首选项屏幕上设置自定义主题。只需在res/values/themes.xml中定义即可。

它会像这样:

<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
  <style name="Theme.DarkText">
    <item name="android:textColor">#000000</item>
  </style>
</resources> 

然后在您的Activity中设置它:

setTheme(R.style.Theme_DarkText);

如果您想在布局构建完成后更改文本颜色,该怎么办? - Rudey
@MarioB 这段代码可以改变首选项的标题文本颜色,但不包括 EditTextPreference。EditTextPreference 标题的属性名称是什么(不是对话框标题)? - shantanu

0
我借鉴了Udinic的想法,但稍作改进。 现在可以随时设置(在这种情况下)PreferenceCategory的颜色,而不仅仅是在填充视图时。
如何做到呢?
首先,创建您自己的定制类,例如:
import android.content.Context;
import android.preference.PreferenceCategory;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MyPreferenceCategory extends PreferenceCategory {

private TextView categoryTitle;

public PincardPreferenceCategory(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

public PincardPreferenceCategory(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
}

public PincardPreferenceCategory(Context context, AttributeSet attrs,
        int defStyle) {
    super(context, attrs, defStyle);
    // TODO Auto-generated constructor stub
}


@Override
protected View onCreateView(ViewGroup parent) {
    categoryTitle =  (TextView)super.onCreateView(parent);
    return categoryTitle;
}


public void setBackgroundColor(int color) {
    categoryTitle.setBackgroundColor(color);
}


public void setTextColor(int color) {
    categoryTitle.setTextColor(color);
}

}

完成后,您必须在XML中定义设置时使用它。

之后,您只需在Java preferenceActivity中使用此循环:

    for (int i = 0; i < getListView().getCount(); i++) {
        Object view = getListView().getItemAtPosition(i);
        if (view instanceof PincardPreferenceCategory) {
            ((PincardPreferenceCategory)view).setBackgroundColor(Color.BLUE);
            ((PincardPreferenceCategory)view).setTextColor(Color.RED);
        }
    }

这里是想法。您可以在任何设置上随时执行此操作。 在使用此代码之前,必须完全加载布局,否则 getListView().getCount() 将返回 0。如果您在 onCreate 中使用它,则不起作用。 如果您想在启动时执行此操作,建议您在 onWindowFocusChanged 方法中执行。

当屏幕无法容纳更多项目时,它将无法工作,因为ListView实现了视图回收并不会创建所有视图。 - Display Name

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接