I wanted to add a text block, but set the actual text content programmatically. My specific need: show app version name at the top of the preference screen.
I got it done following the approach by A.Grandt and Krzysiek, and setting the summary in code.
dev_preferences.xml
:
<Preference
android:key="pref_app_version"
android:persistent="false"
android:selectable="false"
android:title="@string/app_name" />
The preference fragment (extends PreferenceFragment
):
private static final String KEY_APP_VERSION = "pref_app_version";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.dev_preferences);
findPreference(KEY_APP_VERSION).setSummary(BuildConfig.VERSION_NAME);
}
I also ended up using a custom layout (as in this answer) by setting android:layout="@layout/dev_preferences_header"
in the <Preference>
entry. (Not mandatory, but this way you can easily customise the looks of the preference "header".)
dev_preferences_header.xml
:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeight"
android:padding="@dimen/spacing_small">
<TextView
android:id="@android:id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="@android:id/summary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@android:id/title" />
</RelativeLayout>