首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android XML 佈局設計:動態數值顏色變化的自定義 View 思路

     編輯:程式設計疑難解答

需求:六個文字框顯示從伺服器獲取的設定值與實時值,實時值超過設定值時變色。XML 本身無法表達動態邏輯,需結合自定義 View 或 Data Binding 實作。

XML 結構建議

<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>

動態變色實作方案

  1. 自定義 ValueView 繼承 LinearLayout,內含三個 TextView,提供 setThreshold(float)、setCurrent(float) 方法,內部比較並呼叫 setTextColor。
  2. 或使用 Data Binding:在 XML 中寫 android:textColor="@{current > threshold ? @color/red : @color/black}",配合 ObservableField 自動更新。
  3. 若數值頻繁更新,建議用 RecyclerView + DiffUtil 避免整佈局重繪。

XML 只負責靜態結構,動態行為交由 Java/Kotlin 邏輯處理,符合關注點分離原則。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved