Search code examples
androidsharedpreferencesandroid-xmlandroid-preferences

can I add custom attributes to components in preferences.xml without making custom views?


I am trying to store a state or data with some sort of custom attribute to existing components in the preferences.xml that I can later reference and read in code. I want to avoid creating custom views for all of these componenets if possible since that would mean I have to create a new custom view each time someone wants to add an attribute to a new component.

For example, I want to add mycustomatt:forced="true" to certain components as shown below. Is this possible without creating custom views or is there an alternative solution that could be better?

<EditTextPreference
    android:defaultValue="300"
    android:inputType="number"
    android:key="coffeekey"
    mycustomatt:forced="true"
    android:persistent="true"
    android:title="@string/coffee" />
<CheckBoxPreference
    android:defaultValue="false"
    android:key="highprio"
    mycustomatt:forced="true"
    android:persistent="true"
    android:summary="@string/highpriocoffeedesc"
    android:title="@string/highpriocoffee" />
<RingtonePreference
    android:defaultValue="default"
    android:key="notiftone"
    mycustomatt:forced="true"
    android:persistent="true"
    android:ringtoneType="notification"
    android:summary="@string/notitonesum"
    android:title="@string/notitone" />

Solution

  • As @SiddarthJain said in the comments - it seems the best and only way of doing this without creating custom views would be to use android:tag in my components, example below

    <CheckBoxPreference
        android:defaultValue="false"
        android:key="highprio"
        android:tag="forced"
        android:persistent="true"
        android:summary="@string/highpriocoffeedesc"
        android:title="@string/highpriocoffee" />