Sunday, April 1, 2012

Adding TextView to Android PreferenceScreen Layout

If you would like to add a text string inside a PreferenceScreen, do the following

1- Create a normal layout (settings_message.xml)

<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="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20px"
        android:text="@string/settings_text" />

</LinearLayout>



2- Add a PreferenceCategory tag in your PreferenceScreen layout and link it to your previously created layout


<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
        android:title="@string/settings_label"
        android:key="settings">

      
    <ListPreference
            android:key="shapes"
            android:title="@string/shapes_label"
            android:summary="@string/shapes_desc"
            android:entries="@array/shapes_entries"
            android:entryValues="@array/shapes_values" />


      

  <PreferenceCategory


    android:title="Category Title"


    android:layout="@layout/settings_message"


/>


      

  
</PreferenceScreen>


9 comments:

  1. How do you reach the TextView programmatically then? When I call findViewById(R.id.textView1), it returns NULL.

    ReplyDelete
  2. It shoudn't return null, may be there is something wrong somewhere ( may be the name of the field)

    ReplyDelete
  3. How to properly reach the TextView programmatically so the return is not null? Thanks

    ReplyDelete
  4. I have the same problem that cannot get the TextView. I try to find PreferenceScreen first, and then use getView of PreferenceScreen, but it didn't work. Could you tell us how to reach the TextView? Thanks a lot.

    ReplyDelete
  5. Guys, i my project i didn't need to get the text view programatically, so i dont have an answer to this problem, but as i can see the preferene screen does not contain views it contains layouts, so you may try to dig into the layouts to reach the view

    ReplyDelete
  6. Thanks, very usefull post for my android project :)

    ReplyDelete
  7. Thanks a lot man! I used in in may app for displaying legal notice!

    ReplyDelete