How to set a custom style or other background selector drawable for the SwitchPreference widget in Android?
(Note: not the regular Switch widget, I mean the standart SwitchPreference widget that used in PreferenceActivity / PreferenceFragment)
You have to create a custom layout for the switch itself and you can apply it dynamically like.
preference.setWidgetLayoutResource(R.layout.custom_switch);
But I'll go into details and show you exactly how to achieve this.
So, you define your preference in an xml file like preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="YOUR_CATEGORY_TITLE" >
<SwitchPreference
android:key="SWITCH"
android:title="YOUR_TITLE_FOR_SWITCH" />
</PreferenceCategory>
</PreferenceScreen>
Then read it in the onCreate() method inside your PreferenceActivty class:
SwitchPreference pref = (SwitchPreference) findPreference(getString(R.string.SWITCH));
//pref.setChecked(true); // You can check it already if needed to true or false or a value you have stored persistently
pref.setWidgetLayoutResource(R.layout.custom_switch); // THIS IS THE KEY OF ALL THIS. HERE YOU SET A CUSTOM LAYOUT FOR THE WIDGET
pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Here you can enable/disable whatever you need to
return true;
}
});
The custom_switch layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/custom_switch_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:textColor="#android:color/white"
android:textIsSelectable="false"
android:textSize="18sp"
android:textStyle="bold"
android:track="#drawable/switch_track"
android:thumb="#drawable/switch_thumb"/>
And for the switch you'll have 2 selectors for the track and thumb properties.
The drawables for these selectors can be generated with the Android Holo Color Generator, which was suggested by tasomaniac. In this case, all you have to do, is to copy the content of the generated drawable folders(only for the drawable-hdpi, drawable-mdpi, drawable-xhdpi, drawable-xxhdpi). But you can create custom views for each state you need.
Here is how these selectors will look like:
switch_track:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/switch_bg_focused" android:state_focused="true"/>
<item android:drawable="#drawable/switch_bg"/>
</selector>
switch_thumb:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/switch_thumb_disabled" android:state_enabled="false"/>
<item android:drawable="#drawable/switch_thumb_pressed" android:state_pressed="true"/>
<item android:drawable="#drawable/switch_thumb_activated" android:state_checked="true"/>
<item android:drawable="#drawable/switch_thumb"/>
</selector>
And that's pretty much it. This solution helped me out. If I omitted something, please let me know and I'll correct the issues.
You can use the below website to generate style for your Switch.
http://android-holo-colors.com/
And then you can use following libraries to custom implementation of the regular Switch. These libraries also include SwitchPreference alternative.
https://github.com/BoD/android-switch-backport
https://github.com/ankri/SwitchCompatLibrary
One way of doing this is to subclass the SwitchPreference and override the onBindView method. In doing so, you'll want to still call super.onBindView(view) in that method, but then find the Switch in the child views and style it as appropriate:
package com.example;
import android.annotation.SuppressLint;
import android.content.Context;
import android.preference.SwitchPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import com.example.R;
public class CustomSwitchPreference extends SwitchPreference {
#SuppressLint("NewApi")
public CustomSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public CustomSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSwitchPreference(Context context) {
super(context);
}
#Override
protected void onBindView(View view) {
super.onBindView(view);
Switch theSwitch = findSwitchInChildviews((ViewGroup) view);
if (theSwitch!=null) {
//do styling here
theSwitch.setThumbResource(R.drawable.new_thumb_resource);
}
}
private Switch findSwitchInChildviews(ViewGroup view) {
for (int i=0;i<view.getChildCount();i++) {
View thisChildview = view.getChildAt(i);
if (thisChildview instanceof Switch) {
return (Switch)thisChildview;
}
else if (thisChildview instanceof ViewGroup) {
Switch theSwitch = findSwitchInChildviews((ViewGroup) thisChildview);
if (theSwitch!=null) return theSwitch;
}
}
return null;
}
}
Create a style in your style.xml file and give it Widget.AppCompat.CompoundButton.Switch parent.
<style name="theme_switch_compat" parent="Widget.AppCompat.CompoundButton.Switch">
<item name="colorAccent">#color/YourColorAccent</item>
</style>
Then you can use the link below to complete your theme
How to change the track color of a SwitchCompat
Related
I have the following preferences in my preferences.xml:
<SwitchPreference
android:summary="Lorum ipsum dolor sit amet"
android:title="Frobulate" />
<SeekBarPreference android:title="Marglins"/>
<SwitchPreference android:title="Bromzuling" />
The problem with this is that this renders Marglins with a very different style as the titles of the SwitchPreferences:
Is there something I can put in my styles.xml to make the titles look the same in font size, color, alignment etc.?
In your theme, try setting
<item name="preferenceTheme">#style/PreferenceThemeOverlay.v14.Material</item>
In my mock-up, this shows the following:
This is using com.android.support:preference-v7:27.1.1. Since this is the look that you are looking for, use this library if you can.
Make sure that you are consistently using the preference support library and not mixing things up; otherwise, things make not look/work as expected.
Here is a small app that demonstrates styling of the SeekBar preference. The app doesn't really do anything other than display the preferences. This app show the same display as shown above.
AndroidManifest.xml
Nothing fancy here.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.preferencecustomlayout">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name="com.example.preferencecustomlayout.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<!-- Theme for the preferences -->
<item name="preferenceTheme">#style/PreferenceThemeOverlay.v14.Material</item>
</style>
</resources>
app_preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.preference.SwitchPreferenceCompat
android:key="switchPreference1"
android:summary="Lorum ipsum dolor sit amet"
android:title="Frobulate" />
<android.support.v7.preference.SeekBarPreference
android:key="seekBarPreference"
android:title="Marglins" />
<android.support.v7.preference.SwitchPreferenceCompat
android:key="switchPreference1"
android:title="Bromzuling" />
</android.support.v7.preference.PreferenceScreen>
MainActivity.java
Notice all the "v7" imports at the top. Don't let these get away. If things aren't working, check that you are still using the support library.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.preference.PreferenceFragmentCompat;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
Fragment preferenceFragment = new PrefsFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.prefContainer, preferenceFragment);
ft.commit();
}
}
public static class PrefsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle bundle, String s) {
addPreferencesFromResource(R.xml.app_preferences);
}
}
}
activity_main.xml
Just a home for the preference fragment.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/prefContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.preferencecustomlayout.MainActivity" />
As for eliminating the numeric display from the seekbar, that is going to be a little more involved. According to the SeekBarPreference documentation:
The seekbar value view can be shown or disabled by setting showSeekBarValue attribute to true or false, respectively.
Unfortunately, setting this value in the app_preferences.xml file gives an "is private" error. There is also no public method, that I have seen, to set the internal variable that controls this. You could subclass SeekBarPreference, override onBindViewHolder() as follows:
MySeekBarPreference.java
import android.content.Context;
import android.support.v7.preference.PreferenceViewHolder;
import android.support.v7.preference.SeekBarPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
public class MySeekBarPreference extends SeekBarPreference {
public MySeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public MySeekBarPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public MySeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MySeekBarPreference(Context context) {
super(context);
}
#Override
public void onBindViewHolder(PreferenceViewHolder view) {
super.onBindViewHolder(view);
TextView seekBarValueTextView = (TextView) view.findViewById(R.id.seekbar_value);
seekBarValueTextView.setVisibility(View.GONE);
}
}
The above custom seek bar preference class will just get rid of the seek bar value. Change the seek bar definition in app_preferences.xml to:
<com.example.preferencestyleseekbar.MySeekBarPreference
android:key="seekBarPreference"
android:title="Marglins" />
and you will see that the value is no longer shown.
Preferences are generally a mess. I have found a very good series of articles by Jakob Ulbrich regarding preferences and getting them to work and look like material design. You may find it helpful to check them out.
For me, the solution was to use com.android.support:preference-v14 instead of v7. This allowed me to use PreferenceThemeOverlay.v14.Material, which otherwise was not accessible.
I want to set style or font to the text in a TextView like the image shown below:
<TextView
style="#style/CodeFont"
android:text="#string/hello" />
You need to Make that codefont style:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="#android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
Straight from : http://developer.android.com/guide/topics/ui/themes.html
You need a custom font and then you can do this:
Typeface mFont = Typeface.createFromAsset(getAssets(), "fonts/myFont.ttf");
MyTextView.setTypeface(mFont);
You have to create a "fonts" folder in your assets folder. Drop your font in there.
You could also create a custom TextView of course. Refer to this answer, I gave a while back, if you prefer that.
There is another way if you want to change it on many TextViews, Use a class:
public class MyTextView extends TextView {
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Ubuntu-L.ttf");
setTypeface(tf);
}
}
}
and in the Layout replace:
<TextView
...
/>
With:
<com.WHERE_YOUR_CLASS_IS.MyTextView
...
/>
You could create a layout.xml file that would have your textview in it. Something like :
textView.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
style="#android:style/Holo.ButtonBar" >
If you dont want this then you could create your custom style. Something like this :
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Custom" parent="#android:style/TextAppearance.Large" >
<item name="android:typeface">monospace</item>
</style>
</resources>
and in the layout file change the style to something like :
style="#style/Custom"
What I want to do is change the background color (set custom drawable) of a popup error message displayed after using setError() method.
Currently, it looks like this:
I've found that Android has two files:
popup_inline_error.9.png
popup_inline_above_error.9.png
And you're supposed to be able to set them using two attributes:
errorMessageBackground
errorMessageAboveBackground
But when I try to set them in my theme, all I get is:
<item name="errorMessageBackground">#drawable/popup_inline_error_holo_light</item>
<item name="errorMessageAboveBackground">#drawable/popup_inline_error_above_holo_light</item>
error: Error: No resource found that matches the given name: attr 'errorMessageBackground'.
(it's the same with android:errorMessageBackground)
I'm putting this question here, cause I've run out of ideas - maybe someone already managed to do that?
EDIT:
Header of the Theme I'm using:
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style
name="Theme.MyThemeName"
parent="#style/Theme.Sherlock.Light">
ANOTHER EDIT:
Uh, I've found that my question is a duplicate of:
android:errorMessageBackground getting no resource found error in styles.xml
YET ANOTHER EDIT:
This is a known problem, take a look at this link: https://code.google.com/p/android/issues/detail?id=55879
I would suggest to use #Codeversed solution, but if it doesn't fit for you for some reason you can use my custom EditText implementation.
Usual EditText representation:
EditText with error:
In few words: I've created custom xml state for error display. See related code below:
InputEditText.java:
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.EditText;
import com.example.oleksandr.inputedittext.R;
/**
* Input EditText which allows define custom drawable for error state
*/
public class InputEditText extends EditText {
private static final int[] STATE_ERROR = {R.attr.state_error};
private boolean mIsError = false;
public InputEditText(Context context) {
this(context, null, 0);
init();
}
public InputEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public InputEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public InputEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private void init() {
addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// empty
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
setError(null);
}
#Override
public void afterTextChanged(Editable s) {
// empty
}
});
}
#Override
public void setError(CharSequence error) {
mIsError = error != null;
super.setError(error);
refreshDrawableState();
}
#Override
public void setError(CharSequence error, Drawable icon) {
mIsError = error != null;
super.setError(error, icon);
refreshDrawableState();
}
#Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (mIsError) {
mergeDrawableStates(drawableState, STATE_ERROR);
}
return drawableState;
}
}
drawable/edittext_bg_error.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
android:id="#+id/listview_background_shape"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<stroke
android:width="2dp"
android:color="#f00"
/>
<padding
android:bottom="2dp"
android:left="2dp"
android:right="2dp"
android:top="2dp"
/>
<corners android:radius="5dp"/>
<solid android:color="#ffffffff"/>
</shape>
drawable/edittext_bg_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- custom error state drawable -->
<item android:drawable="#drawable/edittext_bg_error" app:state_error="true"/>
<!-- Do whatever you want for all other states -->
<item android:drawable="#android:drawable/editbox_background_normal"/>
</selector>
add to your attrs.xml
<attr name="errorColor" format="reference"/>
and to styleables.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="error">
<attr name="state_error" format="boolean"/>
</declare-styleable>
</resources>
and usage is really simple:
<com.example.oleksandr.inputedittext.views.InputEditText
android:id="#id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/edittext_bg_selector"
android:inputType="text"
android:text="#string/hello_world"
/>
[EDIT]:
Just realized, that original answer was about changing error popup color, but not EditText background color. Anyway, hope this can help someone.
you will need to include these dependancies:
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
and here is a sample on how to use it:
<android.support.design.widget.TextInputLayout
android:id="#+id/input_layout_password"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint_email" />
</android.support.design.widget.TextInputLayout>
This will give you the Material Design you are looking for to give form validation as well as a nice animation effect for the label.
private EditText adTitle;
// ....
adTitle.setError(Html.fromHtml("<font color='red'>hello</font>"));
You can use this method just pass msg text,your edittext id
public static void setErrorMsg(String msg,EditText viewId)
{
//Osama ibrahim 10/5/2013
int ecolor = Color.WHITE; // whatever color you want
String estring = msg;
ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
viewId.setError(ssbuilder);
}
The textColor attribute isn't working. Here's my XML:
<PreferenceCategory
android:title="Title"
android:textColor="#00FF00">
Any ideas?
use this customize PreferenceCategory class :
public class MyPreferenceCategory extends PreferenceCategory {
public MyPreferenceCategory(Context context) {
super(context);
}
public MyPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyPreferenceCategory(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
#Override
protected void onBindView(View view) {
super.onBindView(view);
TextView titleView = (TextView) view.findViewById(android.R.id.title);
titleView.setTextColor(Color.RED);
}
}
and add this at your Pref.xml file :
<ali.UI.Customize.MyPreferenceCategory android:title="#string/pref_server" />
An easy way to do this is to set the custom layout for the preferenceCategory here:
<PreferenceCategory
android:layout="#layout/preferences_category"
android:title="Privacy" >
Then set your code inside your preferences_category layout file:
<TextView
android:id="#android:id/title"
android:textColor="#color/deep_orange_500"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold"
android:textAllCaps="true"/>
One solution is to make a theme for your PreferenceScreen.
So in your themes.xml or styles.xml (better to put it in themes.xml) :
<style name="PreferenceScreen" parent="YourApplicationThemeOrNone">
<item name="android:textColor">#color/yourCategoryTitleColor</item>
</style>
then in your AndroidManifest.xml :
<activity
android:name="MyPreferenceActivity"
...
android:theme="#style/PreferenceScreen" >
</activity>
It worked perfectly for me.
To change text color of preference category only set a theme to your PreferenceActivity in your Android Manifest and make sure that colorAccent item exists. This color is taken by your PreferenceCategory.
Actually just found out that preference category text using colorAccent. If your app didn't using style of colorAccent, you can go to styles.xml and find <item name="colorAccent">#color/colorPrimary</item>, and change the color as you want.
Other way around will be mention the theme in your AppTheme, application level
<style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
.....//your other items
<item name="preferenceTheme">#style/PrefTheme</item>
</style>
<style name="PrefTheme" parent="#style/PreferenceThemeOverlay">
<item name="preferenceCategoryStyle">#style/CategoryStyle</item>
</style>
<style name="CategoryStyle" parent="Preference.Category">
<item name="android:layout">#layout/pref_category_view</item>
</style>
XML : pref_category_view
<?xml version="1.0" encoding="utf-8"?>
<TextView android:id="#android:id/title"
style="?android:attr/listSeparatorTextViewStyle"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:textColor="#color/red"
android:layout_height="wrap_content"
/>
For more customization visit v7 Preferences res
Important: I am using PreferenceFragmentCompat from lib v7 Preference.
Using Material Theme, you just have to override the following property :
<style name="YourTheme" parent="#style/Theme.MaterialComponents">
<item name="colorAccent">#color/your_custom_color</item>
</style>
public class MyPreferenceCategory extends PreferenceCategory {
public MyPreferenceCategory(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyPreferenceCategory(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyPreferenceCategory(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
#Override
protected View onCreateView(ViewGroup parent) {
// It's just a TextView!
TextView categoryTitle = (TextView)super.onCreateView(parent);
categoryTitle.setTextColor(parent.getResources().getColor(R.color.orange));
return categoryTitle;
}
}
And in your prefs.xml:
<com.your.packagename.MyPreferenceCategory android:title="General">
.
.
.
</com.your.packagename.MyPreferenceCategory>
Or you can also use this answer
Define your own PreferenceTheme and override colors.
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="preferenceTheme">#style/AppTheme.PreferenceTheme</item>
</style>
<style name="AppTheme.PreferenceTheme" parent="PreferenceThemeOverlay.v14.Material">
<item name="colorAccent">`#color_value`</item>
</style>
Inspired by #AliSh answer, but I needed to only change the colour of one Preference text item. So, for all the Kotlin guys out there:
class TextColorPreference : Preference {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(
context: Context, attrs: AttributeSet,
defStyle: Int
) : super(context, attrs, defStyle)
override fun onBindViewHolder(holder: PreferenceViewHolder?) {
super.onBindViewHolder(holder)
context?.let {
(holder?.findViewById(android.R.id.title) as? TextView)?.setTextColor(
ContextCompat.getColor(
it,
R.color.colorPrimary
)
)
}
}
}
And then put it in your xml/prefs.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<this.should.be.your.package.TextColorPreference
android:id="#+id/settings_logout"
android:key="#string/prefs_key_logout"
android:title="#string/settings_logout" />
</PreferenceScreen>
For androidx preference library you can extend PreferenceCategory or Preference class like this:
class DangerPreference(
context: Context?,
attrs: AttributeSet?,
): Preference(context, attrs) {
override fun onBindViewHolder(holder: PreferenceViewHolder?) {
super.onBindViewHolder(holder)
holder?.itemView?.findViewById<TextView>(android.R.id.title)?.setTextColor(Color.RED)
}
}
then use it normally in your PreferenceScreen:
<com.github.anastr.myscore.util.pref.DangerPreference
app:key="deleteServerData"
app:title="#string/delete_server_data"
app:iconSpaceReserved="false" />
A lot of the other answers didn't work for my case. I'm using a PreferenceFragmentCompat and I didn't want to have actual code doing this. So I simply made a copy of the preference category xml file and changed the textColor field. The file goes under the Apache license, Version 2.
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (C) 2015 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 -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:layout_marginStart="?android:attr/listPreferredItemPaddingLeft"
android:orientation="vertical">
<TextView
android:id="#android:id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingEnd="?android:attr/listPreferredItemPaddingRight"
android:textAlignment="viewStart"
android:textColor="#color/app_accent"
android:textStyle="bold"
tools:ignore="RtlSymmetry"/>
<TextView
android:id="#android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
android:textColor="?android:attr/textColorSecondary"/>
</LinearLayout>
And imported it in my .xml layout for the Preference fragment:
<PreferenceCategory
android:layout="#layout/preference_category_companion"
android:key="my_preference_title"
android:title="#string/my_preference_title">
I have a PreferenceActivity with two checkboxes. Everything is working correctly, but I have a UI problem; not all of the text for the checkbox fits onto the checkbox row.
Is there a nice way to set the minimum height for these checkbox preferences without hardcoding a value?
EDIT - adding xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="alarm_set"
android:title="#string/set_alarm_title"
android:defaultValue="true" />
<CheckBoxPreference
android:key="store_pages"
android:title="#string/store_downloaded_pages_title"
android:summary="#string/store_downloaded_pages"
android:defaultValue="false" />
</PreferenceScreen>
Based off this question about text preference having the same iussue I use this class.
public class LongSummaryCheckBoxPreference extends CheckBoxPreference
{
public LongSummaryCheckBoxPreference(Context ctx, AttributeSet attrs, int defStyle)
{
super(ctx, attrs, defStyle);
}
public LongSummaryCheckBoxPreference(Context ctx, AttributeSet attrs)
{
super(ctx, attrs);
}
#Override
protected void onBindView(View view)
{
super.onBindView(view);
TextView summary= (TextView)view.findViewById(android.R.id.summary);
summary.setMaxLines(4);
}
}
In the xml it then looks like this.
<com.iforpowell.android.ipbike.LongSummaryCheckBoxPreference android:key="#string/key_distance_line_enable"
android:title="#string/title_distance_line_enable" android:summary="#string/summary_distance_line_enable"
android:defaultValue="true" />
<com.iforpowell.android.ipbike.LongSummaryCheckBoxPreference android:key="#string/key_altitude_line_enable"
android:title="#string/title_altitude_line_enable" android:summary="#string/summary_altitude_line_enable"
android:defaultValue="true" />
I have exactly the same thing for EditTextPreference which has the same problem of a max of 2 lines for the summary in Api <= 7
In the xml you can set the height to "wrap_content". At that point it will size it to fit whatever you put in it. So, something along these lines:
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CheckBox" />
This should help
Just do it this way:
<!-- Application theme -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- Min item height -->
<item name="android:listPreferredItemHeight">10dp</item>
</style>
another styling attributes that can be overridden can be found here preference item layout