編輯:Android 開發實例
自定義控件在 Android 中無所不在。假設某個 UI 是一塊圖片、一個按鈕、一行說明文字的固定組合,而這個組合在 App 裡出現十幾次——難道每次都要重寫三個 tag?既浪費時間、效率又低,還容易寫錯。
更好的做法是封裝成一個自定義 View:既提升效率,在 XML 中使用時也更乾淨美觀。本文分兩部分:屬性定義的語法,以及自定義控件的完整實作。
以下代碼均定義於 values/attrs.xml,屬性名稱可自行命名。
<declare-styleable name = "名稱">
<attr name = "background" format = "reference" />
<attr name = "src" format = "reference" />
</declare-styleable>
<attr name = "textColor" format = "color" />
<attr name = "focusable" format = "boolean" />
<attr name = "layout_width" format = "dimension" />
<attr name = "fromAlpha" format = "float" /> <attr name = "toAlpha" format = "float" />
<attr name = "frameDuration" format = "integer" /> <attr name = "framesCount" format = "integer" />
<attr name = "text" format = "string" />
<attr name = "pivotX" format = "fraction" /> <attr name = "pivotY" format = "fraction" />
<attr name="orientation">
<enum name="horizontal" value="0" />
<enum name="vertical" value="1" />
</attr>
<attr name="windowSoftInputMode">
<flag name = "stateUnspecified" value = "0" />
<flag name = "stateUnchanged" value = "1" />
<flag name = "stateHidden" value = "2" />
<flag name = "stateAlwaysHidden" value = "3" />
</attr>
flag 與 enum 的差別在於:enum 只能選一個,flag 可以用 | 組合成多個,例如 stateHidden|stateAlwaysHidden。因此 flag 的值通常會設計成 1、2、4、8 這類可組合的位元值。
<attr name = "background" format = "reference|color" />
這樣一來,這個屬性既能接受 @drawable/xxx 也能接受 #FFFFFF。
目標:做一個「帶陰影的按鈕,按鈕正下方有文字說明」的複合控件(類似九宮格入口)。
新建 values/attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="custom_view">
<attr name="custom_id" format="integer" />
<attr name="src" format="reference" /> <!-- 按鈕圖 -->
<attr name="background" format="reference" /> <!-- 陰影背景 -->
<attr name="text" format="string" /> <!-- 按鈕說明 -->
<attr name="textColor" format="color" />
<attr name="textSize" format="dimension" />
</declare-styleable>
</resources>
public class CustomView extends FrameLayout implements OnClickListener {
private CustomListener customListener = null;
private Drawable mSrc = null, mBackground = null;
private String mText = "";
private int mTextColor = 0;
private float mTextSize = 20;
private int mCustomId = 0;
private ImageView mBackgroundView = null;
private ImageButton mButtonView = null;
private TextView mTextView = null;
private LayoutParams mParams = null;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
// 讀取 XML 中宣告的自定義屬性
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.custom_view);
mSrc = a.getDrawable(R.styleable.custom_view_src);
mBackground = a.getDrawable(R.styleable.custom_view_background);
mText = a.getString(R.styleable.custom_view_text);
mTextColor = a.getColor(R.styleable.custom_view_textColor, Color.WHITE);
mTextSize = a.getDimension(R.styleable.custom_view_textSize, 20);
mCustomId = a.getInt(R.styleable.custom_view_custom_id, 0);
mTextView = new TextView(context);
mTextView.setTextSize(mTextSize);
mTextView.setTextColor(mTextColor);
mTextView.setText(mText);
mTextView.setGravity(Gravity.CENTER);
mTextView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mButtonView = new ImageButton(context);
mButtonView.setImageDrawable(mSrc);
mButtonView.setBackgroundDrawable(null);
mButtonView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mButtonView.setOnClickListener(this);
mBackgroundView = new ImageView(context);
mBackgroundView.setImageDrawable(mBackground);
mBackgroundView.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
addView(mBackgroundView);
addView(mButtonView);
addView(mTextView);
this.setOnClickListener(this);
a.recycle(); // 用完務必回收,否則會浪費記憶體
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
// 陰影與按鈕靠上置中,說明文字靠下置中
mParams = (LayoutParams) mButtonView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
mButtonView.setLayoutParams(mParams);
}
mParams = (LayoutParams) mBackgroundView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
mBackgroundView.setLayoutParams(mParams);
}
mParams = (LayoutParams) mTextView.getLayoutParams();
if (mParams != null) {
mParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
mTextView.setLayoutParams(mParams);
}
}
public void setCustomListener(CustomListener l) {
customListener = l;
}
@Override
public void onClick(View v) {
if (customListener != null) {
customListener.onCuscomClick(v, mCustomId);
}
}
public interface CustomListener {
void onCuscomClick(View v, int custom_id);
}
}
兩個關鍵點:obtainStyledAttributes() 是讀取自定義屬性的入口,而 a.recycle() 是必須的收尾;CustomListener 介面則讓控件能把點擊事件連同 custom_id 往外拋,呼叫方就能分辨是哪一個實例被點擊。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:nanlus="https://schemas.android.com/apk/res/com.nanlus.custom"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="horizontal">
<com.nanlus.custom.CustomView
android:id="@+id/custom1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
nanlus:background="@drawable/background"
nanlus:custom_id="1"
nanlus:src="@drawable/style_button"
nanlus:text="按鈕1" />
</LinearLayout>
</RelativeLayout>
這裡有兩行需要解釋:
· xmlns:nanlus="https://schemas.android.com/apk/res/com.nanlus.custom"——nanlus 是你在 XML 中使用自定義屬性的前綴(名稱可自取),而 com.nanlus.custom 必須是控件所在的套件名稱。這個 URI 的格式是固定的,最後一段就是 package name。
· 標籤本身要用社完整類名 <com.nanlus.custom.CustomView>,因為它是自定義類別而非內建控件。
public class CustomActivity extends BaseActivity implements CustomListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((CustomView) this.findViewById(R.id.custom1)).setCustomListener(this);
}
@Override
public void onCuscomClick(View v, int custom_id) {
switch (custom_id) {
case 1:
Toast.makeText(this, "hello !!!", Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
}
自定義控件的價值在於「一次封裝,到處複用」。定義屬性時依資料性質挑選正確的 format,能讓 XML 在編譯期就幫你檢查型別錯誤;而透過自訂 Listener 介面把事件往外拋,則是讓複合控件保持彈性的標準手法。
補充一個實務建議:宣告 <declare-styleable> 時,名稱必須與控件類別的簡單類名一致(本例中 CustomView 對應 custom_view,這是 Android 工具鏈的約定),否則 R.styleable 中不會生成對應的常數。若一個 attrs.xml 裡有多個控件,各自用一組 declare-styleable 即可。
ListView 分頁加載實作:滚动到底自動載入更多資料
ListView 是 Android 最常用的控件之一。實務上如果一次把幾千筆資料塞進去,畫面會卡、記憶體會爆,因此分頁加載幾乎是必備技巧。 本範例把「載入更多」的觸發點
Android 遊戲開發實踐:角色移動時的地圖平滑滾動處理
先看效果: 地圖滾動的原理 此前寫過角色在屏幕內移動的方式,但那時拼出來的地圖正好鋪滿整個屏幕,因此不必操心滾動問題。當地圖大於屏幕時,事情就複雜了:既要讓角色看起來
Android 載入動畫:Spinner 的屬性、方法與按鈕範例
Spinner 是 Android 中常見的載入提示元件。它通常搭配 ProgressBar 使用,適合表示「目前有工作進行中,但完成時間未知」的狀態。 建立 Spin
Android 進度指示器:不確定模式的 Spinner 怎麼用
當 App 要執行一段耗時的工作,使用者需要知道「系統還在動」。Android 用 ProgressBar 來表達這件事,而它基本上有兩種形態:進度條(progress