Cosimo Sguanci Cosimo Sguanci - 1 month ago 20
Android Question

Adding custom layout to PreferenceFragment

I have a preference fragment with a preference screen hierarchy. I would like to add a custom layout to define an "about the author" section, adding imageview to an element and a link (intent to browser). I searched but I didn't find any resources about this topic.

Answer

In your preference xml file (res/xml/prefs.xml), add a Preference with a custom layout:

<Preference
    android:layout="@layout/custom_preference"/>

Example of layout/custom_preference.xml with an ImageView and a TextView with a link that will be opened in the browser:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_book" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="http://www.mylink.com"
        android:autoLink="all"/>
</LinearLayout>

It's the last preference in the screenshot: preference screen with custom preference

Comments