Skip to content

Instantly share code, notes, and snippets.

@flocsy
Created February 11, 2016 13:33
Show Gist options
  • Save flocsy/f22b4b1d8d38321b06a6 to your computer and use it in GitHub Desktop.
Save flocsy/f22b4b1d8d38321b06a6 to your computer and use it in GitHub Desktop.
display your app's version in preferences screen
package com.fletech.android.preference;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.preference.Preference;
import android.util.AttributeSet;
/*
Author: Gavriel Fleischer <[email protected]>
Use VersionPreference to display the compiled version of your app in your preferences activity.
res/xml/preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<com.fletech.android.preference.VersionPreference android:title="@string/pref_title_version" />
</PreferenceScreen>
res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="pref_title_version">Version</string>
</resources>
*/
public class VersionPreference extends Preference {
public VersionPreference(Context context, AttributeSet attrs) {
super(context, attrs);
String versionName;
final PackageManager packageManager = context.getPackageManager();
if (packageManager != null) {
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
versionName = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = null;
}
setSummary(versionName);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment