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.
-
The `RelativeLayout` should do the job. – Merve Sahin Oct 30 '16 at 20:49
-
Ok but where i have to link the layout to the fragment? In the preference fragment class or in the xml? – Cosimo Sguanci Oct 30 '16 at 20:50
2 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>

- 1,574
- 17
- 18
-
11I successfully add the custom layout to my preferencefragment, but how to reference the view within the preference fragment class ? i need to interact with that view to attach on click listener to the button that i add in the custom layout. – 2MuchSmoke Jan 26 '17 at 08:09
-
2
-
2
-
-
@KaranveerSingh nope, i ended up using ordinary fragment to customize the layout. – 2MuchSmoke Mar 29 '18 at 10:03
-
1@2MuchSmoke Ok. Although, I just did it by creating a custom Preference and accessing the layout in onBindViewHolder(). – Karanveer Singh Mar 29 '18 at 11:25
-
-
1How can i have a on click listener on this and call the layout screen to pop up as a dialog ? – Ravi Parmar Aug 21 '18 at 10:25
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

- 7,051
- 1
- 53
- 59