Search code examples
androidsharedpreferencespreferencespreferenceactivitytextcolor

How can I change the summary text color of a Preference programmatically?


I am trying to change the text color of a Preference when the user input a incorrect value, similar as web forms do. I found in this question how to access the text view of the summary but the color is not being changed. The code I am using is this:

LinearLayout ly = (LinearLayout) userPasswordPref.getView(null, getListView());
TextView summarytv = (TextView) ((RelativeLayout) ly.getChildAt(1)).getChildAt(1);
summarytv.setTextColor(Color.RED);

UserPasswordPref is of type Preference. How could I change the color?


Solution

  • I found a solution, I have had to create a layout with the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView
        android:id="@android:id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    
    <TextView
        android:id="@android:id/summary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textColor="@color/red" />
    
    </LinearLayout>
    

    An then, in my code:

    userPasswordPref.setLayoutResource(R.layout.summary_error);
    userPasswordPref.setSummary(R.string.error_summary);
    

    Where userPasswordPref is a Preference, and summary_error is the layout above.

    Source: elbauldelprogramador