Home » Android » android – Adding custom layout to PreferenceFragment

android – Adding custom layout to PreferenceFragment

Posted by: admin June 15, 2020 Leave a comment

Questions:

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.

How to&Answers:

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

Answer:

This is just a follow up to the answer by Carmen (30 October 2016):

If you want to dynamically change the properties on your custom layout, after the screen has loaded, you cannot use something like this:

PreferenceScreen customPref = (PreferenceScreen) findPreference("customPreference");
View prefRow = customPref.getView(null, null);
ImageView imageView = (ImageView)prefRow.findViewById(R.id.image_view);
imageView.setImageResource(R.drawable.whatever);

Although it won’t crash, it will not actually do anything. It’s odd and confusing.

You have to use a custom class that extends android.preference.Preference and override onBindView() to change properties on the custom layout. The technique is explained here: How to manage custom preference layout [Note: For PreferenceFragmentCompat, you have to extend androidx.preference.Preference and override onBindViewHolder()]

Another way is to use getView() but ensure that you use View view = super.getView(convertView, parent);: Android Set Custom Preference Layout