Skip to content

Instantly share code, notes, and snippets.

@Kahtaf
Created August 3, 2017 03:21
Show Gist options
  • Save Kahtaf/157b395988a652ac56e47c08f582492b to your computer and use it in GitHub Desktop.
Save Kahtaf/157b395988a652ac56e47c08f582492b to your computer and use it in GitHub Desktop.
Android Preferences - Reusable widget layout for a preference and it's onClick listener
<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:key="preference_key"
android:title="@string/pref_title"
android:widgetLayout="@layout/preference_secondary_button" />
</PreferenceScreen>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/preference_secondary_action"
android:onClick="onPreferenceSecondaryButtonClicked"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:src="@drawable/ic_refresh_white_24dp"
android:tint="@color/ui_medium_gray"/>
</RelativeLayout>
// Parent activity of the preference screen
// onClick listener for reusable preference widget.
public void onPreferenceSecondaryButtonClicked(View view){
// Gets a reference to the preference that contains this widget
ListView preferenceList = (ListView) view.getParent().getParent().getParent();
int preferencePosition = preferenceList.getPositionForView(view);
Preference preference = (Preference) preferenceList.getAdapter().getItem(preferencePosition);
// Add onclick logic here, using reference to the preference object that contains this widget
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment