Цвет текста фрагмента Android Preference - программирование
Подтвердить что ты не робот

Цвет текста фрагмента Android Preference

Я хочу изменить цвет текста в фрагменте предпочтений андроида. В настоящее время я использую настраиваемую тему для изменения изображения флажка, фона, подсветки onClick, и все это отлично работает... кроме цвета текста. Я не хочу использовать тему по умолчанию, я хочу иметь свою собственную тему, поэтому все выглядит так, как я хочу, но просто меняю цвет текста, может кто-то помочь.

styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="selectedTextStyle">  
        <item name="android:textSize">18sp</item>
    </style>
    <style name="buttonTextStyle">  
        <item name="android:textSize">20sp</item>
    </style>
    <style name="PreferencesTheme" >
        <item name="android:windowBackground">@drawable/lists_background</item>
        <item name="android:listViewStyle">@style/listViewPrefs</item>
        <item name="android:checkboxStyle">@style/MyCheckbox</item>

    </style>
    <style name="MyTextAppearance" parent="@android:style/TextAppearance">
        <item name="android:textColor">@color/black</item>
      </style>
    <style name="listViewPrefs" parent="@android:Widget.ListView">
        <item name="android:listSelector">@layout/list_selector_master</item>
        <item name="android:textAppearance">@style/MyTextAppearance</item>
    </style>
    <style name="MyCheckbox" parent="android:Widget.CompoundButton.CheckBox">
        <item name="android:button">@drawable/btn_check</item>
    </style>

</resources>

манифеста:

        <activity
            android:name="com.package.SettingsActivity"
            android:theme="@style/PreferencesTheme"
            android:configChanges="keyboard|orientation" >
        </activity>

Активность:

import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;

public class SettingsActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();

    }
    public static class SettingsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.preferences);

        }
    }

}
4b9b3361

Ответ 1

Вот два объекта TextView из preference.xml (макет для Preference):

    <TextView android:id="@+android:id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal" />

    <TextView android:id="@+android:id/summary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@android:id/title"
        android:layout_alignLeft="@android:id/title"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="?android:attr/textColorSecondary"
        android:maxLines="4" />

Похоже, вы можете переопределить textAppearanceLarge и textColorSecondary в своей теме, чтобы добиться изменения цвета. Вот пример:

<style name="AppTheme">
    <item name="android:textAppearanceLarge">@style/MyTextAppearance</item>
    <item name="android:checkboxStyle">@style/MyCheckBox</item>
</style>

<style name="MyCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
    <item name="android:button">@android:drawable/btn_star</item>
</style>

<style name="MyTextAppearance" parent="@android:style/TextAppearance.Large">
    <item name="android:textColor">#ff0000</item>
</style>

Ответ 2

Я думаю, что простой и понятный способ сделать это следующий:

RES/значения/styles.xml

<style name="SettingsFragmentStyle">

    <item name="android:textColorSecondary">#222</item>
    <item name="android:textColor">#CCC</item>
    <item name="android:background">#999</item>
    ...
</style>

В Activity, который содержит подкласс PreferenceFragment внутри onCreate:

setTheme(R.style.SettingsFragmentStyle);

Ответ 3

Только что нашел ответ, который выполняет свою работу.

Этот файл является макетом по умолчанию для элемента списка предпочтений:

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- Layout for a Preference in a PreferenceActivity. The
     Preference is able to place a specific widget for its particular
     type in the "widget_frame" layout. -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical"
    android:paddingRight="?android:attr/scrollbarSize"
    android:background="?android:attr/selectableItemBackground" >

    <ImageView
        android:id="@+android:id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dip"
        android:layout_marginRight="6dip"
        android:layout_marginTop="6dip"
        android:layout_marginBottom="6dip"
        android:layout_weight="1">

        <TextView android:id="@+android:id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:ellipsize="marquee"
            android:fadingEdge="horizontal" />

        <TextView android:id="@+android:id/summary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@android:id/title"
            android:layout_alignLeft="@android:id/title"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textColor="?android:attr/textColorSecondary"
            android:maxLines="4" />

    </RelativeLayout>

    <!-- Preference should place its actual preference widget here. -->
    <LinearLayout android:id="@+android:id/widget_frame"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical" />

</LinearLayout>

Вы можете использовать его как базу и создать свой собственный макет. Этот макет должен применяться в каждом Предпочтении, подобном этому

<Preference android:key="somekey" 
android:title="Title" 
android:summary="Summary" 
android:layout="@layout/custom_preference_layout"/>

Вы можете изменить весь макет вне списка, вам просто нужно иметь файл макета, содержащий список, в котором настройки будут заполняться следующим образом:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Something" />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

Чтобы переопределить макет по умолчанию для PreferenceFragment, переопределите метод onCreateView и измените раздутое представление:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.custom_options_layout, null);
}

Исходя из этих ответов:

Создание настраиваемого макета для настроек

Как добавить кнопку на экран предпочтений

Android: Как настроить Margin/Padding в предпочтении?

Ответ 4

Не хватает комментариев для комментариев или продвижения, но я просто хотел добавить, что предложение mharper о TextAppearanceMedium также работало для меня в отношении изменения цвета текста. Если кто-то знает, почему это так, объясните это.

Поэтому просто настройте принятый ответ так:

<style name="AppTheme">
     <item name="android:textAppearanceMedium">@style/MyTextAppearance</item>
</style>

<style name="MyTextAppearance" parent="@android:style/TextAppearance.Medium">
     <item name="android:textColor">#ff0000</item>
</style>

По крайней мере, если никто не может объяснить, почему это так, это может помешать кому-то с той же трудностью, что я пытался изменить цвет текста.

Ответ 5

Мне ничего из вышеперечисленных методов не удалось. Я закончил тем, что расширил класс Prefernces, который я использовал, в моем случае CheckBoxPrefernces:

 public class MyPreferenceCheckBox extends CheckBoxPreference {

    public MyPreferenceCheckBox(Context context) {
        super(context);
    }
    public MyPreferenceCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public MyPreferenceCheckBox(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected View onCreateView(ViewGroup parent) {
        ViewGroup root = (ViewGroup) super.onCreateView(parent);
        ((TextView)root.findViewById(android.R.id.title)).setTextColor(parent.getResources().getColor(R.color.red));
        ((TextView)root.findViewById(android.R.id.summary)).setTextColor(parent.getResources().getColor(R.color.red));
        return root;
    }
}

И использование в prefs.xml:

 <com.my.package.name.MyPreferenceCheckBox
        android:title="@string/my_title"
        android:defaultValue="true"
        android:key="@string/my_key"
        android:summary="On/Off" />

Этот ответ показал мне этот путь:

Ответ 6

Мне удалось изменить цвет текста в PreferenceFragment с помощью этого:

styles.xml

<resources>

    <style name="SettingsTheme" parent="android:Theme.Holo">
        <item name="android:textColorPrimary">@color/light_blue_font_color</item>
        <item name="android:textColorSecondary">@color/white_font_color</item>
        <item name="android:textColorTertiary">@color/white_font_color</item>
    </style>

</resources>

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="light_blue_font_color">#33b5e5 </color>
    <color name="white_font_color">#ffffff </color>
</resources>

AndroidManifest.xml

<activity
    android:name="xx.yy.zz.SettingsActivity"
    android:theme="@style/SettingsTheme" >
</activity>

Ответ 7

Если вы используете библиотеку совместимости, просто добавьте:

<item name="colorAccent">#ff0000</item>

в ваш стиль

Ответ 8

Я работаю с min API 11 и компилирую 23. задавать тему и после заданного фона для этой темы. если вы работаете s > API 14, вы можете использовать Theme_DeviceDefault.

Это самое простое решение, которое я нахожу:

public static class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getActivity().setTheme(android.R.style.Theme_Holo);
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.settings);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if(view != null){
            view.setBackgroundColor(ContextCompat.getColor(getActivity(), android.R.color.background_dark));
        }
    }
}