在使用 LWUIT 開發複雜界面時,頁面眾多且組件繁多,常用的 Label、Button、TextField、TextArea 等組件若逐一設置樣式,代碼會顯得極其臃腫。雖然 LWUIT 的 Style 機制類似 Web 中的 CSS,能自定義 Border、Font、FgColor、BgColor、Margin、Padding 等屬性,但大多數組件同時擁有 Style(未選中)、selectedStyle(選中),可點擊的 Button 及其子類還有 pressedStyle(按下)。僅調用 this.getStyle().setBorder(border) 只能設置未選中狀態,一旦組件被選中,樣式便會恢復系統默認值。
一個頁面若有幾十個組件,每個都要分別設置選中與未選中的樣式,雖然單行代碼簡單,但累積起來至少一半代碼都在佈局與樣式設置上,嚴重影響可讀性與維護性。
好在 LWUIT 是開源的,我們可以修改源碼來簡化樣式設置。找到 Component.java,添加以下工具方法,統一處理普通狀態與選中狀態:
// 1469 行起添加的代碼
/**
* 設置自定義 Font(同時應用於未選中與選中狀態)
* @param font 字體對象
*/
public void setCustomFont(Font font) {
this.getStyle().setFont(font);
this.getSelectedStyle().setFont(font);
}
/**
* 設置水平方向 Margin
* @param margin 邊距值
*/
public void setCustomHorizontalMargin(int margin) {
this.getStyle().setMargin(Component.LEFT, margin);
this.getStyle().setMargin(Component.RIGHT, margin);
this.getSelectedStyle().setMargin(Component.LEFT, margin);
this.getSelectedStyle().setMargin(Component.RIGHT, margin);
}
/**
* 設置自定義 Border
* @param border 邊框對象
*/
public void setCustomBorder(Border border) {
this.getStyle().setBorder(border);
this.getSelectedStyle().setBorder(border);
}
/**
* 設置自定義前景色
* @param unselectedColor 未選中時顏色
* @param selectedColor 選中時顏色
*/
public void setCustomFgColor(int unselectedColor, int selectedColor) {
this.getStyle().setFgColor(unselectedColor);
this.getSelectedStyle().setFgColor(selectedColor);
}
/**
* 批量設置完整 Style
* @param unselectedStyle 未選中狀態 Style
* @param selectedStyle 選中狀態 Style
*/
public void setCustomStyle(Style unselectedStyle, Style selectedStyle) {
this.setStyle(unselectedStyle);
this.setSelectedStyle(selectedStyle);
}
Button 及其子類擁有 pressedStyle,需重寫上述方法以覆蓋按下狀態:
// 301 行起添加的代碼
public void setCustomFont(Font font) {
super.setCustomFont(font);
this.getPressedStyle().setFont(font);
}
public void setCustomBorder(Border border) {
super.setCustomBorder(border);
this.getPressedStyle().setBorder(border);
}
public void setCustomFgColor(int unselectedColor, int selectedColor, int pressedColor) {
super.setCustomFgColor(unselectedColor, selectedColor);
this.getPressedStyle().setFgColor(pressedColor);
}
public void setCustomStyle(Style unselectedStyle, Style selectedStyle, Style pressedStyle) {
super.setCustomStyle(unselectedStyle, selectedStyle);
this.setPressedStyle(pressedStyle);
}
修改基礎組件後,即可靈活復用。以 Button 為例,應用中常需無邊框、無背景、帶下劃線(超鏈接風格)等樣式,可將其歸類到 CustomButton 中:
import com.sun.lwuit.Button;
import com.sun.lwuit.Image;
public class CustomButton extends Button {
public CustomButton() {}
public CustomButton(String text) {}
public CustomButton(String text, Image icon) {}
public CustomButton(String text, Image icon, int direction) {}
/** 無邊框按鈕 */
public void setNoBorder() { /* 實現邏輯 */ }
/** 無背景按鈕 */
public void setNoBg() { /* 實現邏輯 */ }
/** 無邊框、無背景按鈕 */
public void setNoBorderBg() { /* 實現邏輯 */ }
/** 超鏈接風格按鈕 */
public void setURLStyle() { /* 實現邏輯 */ }
}
具體方法主體與參數可根據項目需求自行實現。此法大幅減少重複代碼,提升開發效率。
提示:筆者使用的是 1.3 版本前的最新源碼(反編譯 LWUIT.jar 並修復混淆錯誤),可從 此處下載。