How to Bind Data to Android Preference

531 views Asked by At

I want to have a custom SwitchPreference layout and pass the "title" parameter to it, similar to this:

<SwitchPreference
            android:key="@string/key"
            app:passedTitle="@{@string/title}"
            android:layout="@layout/custom_layout"
            android:defaultValue=5 />

that way I can reuse the same layout for the different SwitchPreferences but change the title shown.

I know I can bind data normally as follows:

<include
        layout="@layout/custom_layout"
        app:passedTitle="@{@string/title}"

in conjunction with a custom layout like this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools" >

    <data>
    <variable
        name="passedTitle"
        type="String"/>
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            style="@style/SettingsSubHeader"
            android:text="@{passedTitle}" />

        <!-- Must have this id or else won't save value! -->
        <Switch
            android:id="@android:id/checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"/>

    </RelativeLayout>

</layout>

However, I can't get the passedTitle value to pass to the custom view if I just set them using the andriod:layout param in SwitchPreference (since I can't use <include>).

Do you have any idea how I can pass a value to my custom layout when using a preference?

0

There are 0 answers