数据绑定文本大写

时间:2017-10-31 07:08:56

标签: java android data-binding android-databinding capitalization

我的XML文件看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="name"
            type="com.example.android.model.Name"/>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/text_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_gravity="center"
            android:hint="@string/app_name"
            android:padding="8dp"
            android:text="@{name.title + ' ' + name.first + ' ' + name.last}"
            android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
    </LinearLayout>
</layout>

POJO课程是:

public class Name {

    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("first")
    @Expose
    private String first;
    @SerializedName("last")
    @Expose
    private String last;
}

回复以小写字母出现,即

title = mr
first = jon
last = skeet

我知道多种方式&amp;从Java文件中进行资本化的策略,但是有没有办法利用 XML文件本身中的数据绑定来代替每个单词的首字母而不是将相应Java文件中的每个单词的首字母大写

2 个答案:

答案 0 :(得分:1)

设置BindingAdapter,例如reference

@BindingAdapter({"name_text"})
public static void setName(TextView textView, Name name) {
    String string = String.valueOf((name.title).charAt(0)).toUpperCase() + name.title.substring(1)
            + " " + String.valueOf((name.first).charAt(0)).toUpperCase() + name.first.substring(1)
            + " " + String.valueOf((name.last).charAt(0)).toUpperCase() + name.last.substring(1);
    textView.setText(string);
}

并将TextView指定为:

<TextView
    android:id="@+id/text_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_gravity="center"
    android:hint="@string/app_name"
    android:padding="8dp"
    app:name_text="@{name}"
    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>

答案 1 :(得分:0)

TextView将如下:

<TextView
    android:id="@+id/text_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_gravity="center"
    android:hint="@string/app_name"
    android:padding="8dp"
    android:text="@{String.valueOf(name.title.charAt(0)).toUpperCase()
         + name.title.substring(1) + ' '
         + String.valueOf(name.first.charAt(0)).toUpperCase()
         + name.first.substring(1) + ' '
         + String.valueOf(name.last.charAt(0)).toUpperCase()
         + name.last.substring(1)}"
    android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>