需求:六個文字框顯示從伺服器獲取的設定值與實時值,實時值超過設定值時變色。XML 本身無法表達動態邏輯,需結合自定義 View 或 Data Binding 實作。
<LinearLayout android:orientation="vertical">
<!-- 重複六次,或用 RecyclerView -->
<LinearLayout android:orientation="horizontal">
<TextView android:id="@+id/label" />
<TextView android:id="@+id/setValue" />
<TextView android:id="@+id/currentValue" />
</LinearLayout>
</LinearLayout>
ValueView 繼承 LinearLayout,內含三個 TextView,提供 setThreshold(float)、setCurrent(float) 方法,內部比較並呼叫 setTextColor。android:textColor="@{current > threshold ? @color/red : @color/black}",配合 ObservableField 自動更新。RecyclerView + DiffUtil 避免整佈局重繪。XML 只負責靜態結構,動態行為交由 Java/Kotlin 邏輯處理,符合關注點分離原則。