顯示具有 custom component 標籤的文章。 顯示所有文章
顯示具有 custom component 標籤的文章。 顯示所有文章

2017年5月9日 星期二

Android Custom Component

如下圖,這是一個購物車常見的購買份數選擇。
將「減」按鈕、「加」按鈕及中間的數值,做成一個Component
這樣的好處是你的Activity會比較乾淨,加減Button的Click事件及邏輯在component處理,而不在Activity。

在做單元測試時,也會較方便,單獨針對這個Component測試就好。



新增一個 NumberSelect Layout


這個Layout裡有一個「-」Button、「+」Button、TextView數字

設定custom attributes


在 values 裡新增 attrs.xml ,分別是min_value最小值、max_value最大值、default_value預設值。


在Layout 設定屬性


attrs.xml 這裡設定好了之後,就可直接在layout上設定defaultValue、minValue、maxValue屬性。


建立NumberSelect.java


這段程式有點長,見下方的說明。

在init 裡,取得在layout的min_value、max_value、default_value屬性。



設定addButton、minusButton,加減份數時,異動中間的數值及設定callback



使用custom component


activity_main.xml 加入NumberSelect Custom Component



完整程式


https://github.com/evanchen76/ComponentSample

參考

Custom Components