LoginSignup
6
3

More than 5 years have passed since last update.

DataBindingで属性リソースを利用する

Posted at

DataBindingの属性記法(android:text="@{name}"みたいに書くやつ)で属性リソース(?attr)を使う方法です。

問題

普通にandroid:text="@{?attr/name}"とに書くと、以下のようなエラーが出ます。

image

要するに?を先頭に使ってはいけないということですね。

解決策

解決策は少し面倒ですが、とてもシンプルです。
R.javaファイルをimportして、それを解決した値を渡してやります。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <import type="com.sakuna63.sandbox.R" />
        <import type="com.sakuna63.sandbox.Attrs" />
    </data>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{Attrs.resolveString(context, R.attr.name)}" />
</layout>

public class Attrs {
    public static String resolveString(@NonNull Context context,
                                       @StringRes int attrRes) {
        TypedArray a = null;
        try {
            a = context.obtainStyledAttributes(new int[]{attrRes});
            return a.getString(0);
        } finally {
            if (a != null) {
                a.recycle();
            }
        }

    }
}
6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3