前提・実現したいこと
データバインディングを利用して
文字色をKotlin側で書き換えられるようにしたいのですが、
下記のように書くと、コンパイルも通り、表示もされるものの、文字色が反映されません。
もし原因わかる方入ればご教授いただけると幸いです。
ソースコード
Kotlin
1import android.databinding.* 2import android.view.View 3import jp.example.test.R 4 5class TestViewModel { 6 // 文字数カウンターの文字色 7 // ※※※※※※※このデフォルトの文字色が反映されない※※※※※※※ 8 var text_color_OF = ObservableField<Int>(R.color.Red) 9 10 // 入力ボックス 11 var text_OF = ObservableField<String>() 12 // 文字数カウンター 13 var counter_text_OF = ObservableField<String>("[ 0 / 1000]") 14 15 // 入力ボックスに値が入れられたタイミングで呼び出される 16 // android:onTextChanged="@{(s,i,b,c) -> question.setCounterText(s)}" 17 fun setCounterText(s: CharSequence){ 18 // [ 0 / 1000]という文字列を生成。ここはうまく反映される。 19 text_OF.set(counterText(s, max_length)) 20 21 // ※※※※※※※以下の文字色変更も反映されない※※※※※※※ 22 if((s?.length ?: 0) <= max_length){ 23 text_color_OF.set(R.color.Black) 24 }else{ 25 text_color_OF.set(R.color.Red) 26 } 27 } 28}
XML
1<?xml version="1.0" encoding="utf-8"?> 2<layout xmlns:android="http://schemas.android.com/apk/res/android"> 3 <!-- Binding Objects --> 4 <data> 5 <variable 6 name="question" 7 type="jp.example.test.TestViewModel" /> 8 </data> 9<android.support.constraint.ConstraintLayout 10 xmlns:app="http://schemas.android.com/apk/res-auto" 11 xmlns:tools="http://schemas.android.com/tools" 12 android:layout_width="match_parent" 13 android:layout_height="match_parent" 14 android:background="@color/White"> 15 16 <EditText 17 android:id="@+id/q1_edit" 18 style="@style/EditTextStyle" 19 android:layout_width="match_parent" 20 android:layout_height="150dp" 21 android:text="@={question.text_OF}" 22 android:ems="10" 23 android:inputType="textMultiLine" 24 android:onTextChanged="@{(s,i,b,c) -> question.setCounterText(s)}" 25 android:onFocusChange="@{(v, hasFocus) -> question.FocusChange(hasFocus)}" 26 android:textAppearance="@style/EditText" /> 27 28 29 <TextView 30 android:id="@+id/q1_counter" 31 style="@style/TextStyle.Counter" 32 android:text="@{question.counter_text_OF}" 33 android:textColor="@{question.text_color_OF}"<!-- こいつがうまくいかない --> 34 android:layout_width="match_parent" 35 android:layout_height="wrap_content" 36 android:textAppearance="@style/BoxCounter" />
/res/values/colors.xml
xml
1<?xml version="1.0" encoding="utf-8"?> 2<resources> 3 <color name="Black">#111111</color> 4 <color name="Red">#E80015</color> 5</resources>
以下なら意図通りの色が表示される
[Kotlin] var text_color_OF = ObservableField<Boolean>(false) //setCounterText()の変更は省略 [XML] android:textColor="@{question.text_color_OF ? @color/Black : @color/Red}"
ただ、できればViewModel内で管理をできるようにしたいです。
補足情報
kotlin_version = '1.3.21'
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/03/14 10:52