編輯:關於 Android 程式設計
每個 App 幾乎都有一條頂部標題列:左邊返回、中間標題、右邊操作。與其每個頁面重寫一次,不如封裝成自定義控件,透過 XML 屬性就能設定文字、顏色、背景。本文以 TopBar 為例走一遍完整流程。
在 res/values/ 下建立 attrs.xml,用 declare-styleable 宣告這組屬性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TopBar">
<attr name="titleText" format="string" />
<attr name="titleTextSize" format="dimension" />
<attr name="titleTextColor" format="color" />
<attr name="leftText" format="string" />
<attr name="leftBackground" format="reference|color" />
<attr name="leftTextColor" format="color" />
<attr name="rightText" format="string" />
<attr name="rightBackground" format="reference|color" />
<attr name="rightTextColor" format="color" />
</declare-styleable>
</resources>
format 決定這個屬性接受什麼型別:string 文字、dimension 尺寸(如 15sp)、color 顏色、reference|color 表示「資源參照或顏色值皆可」——後者讓你能同時寫 @drawable/blue 和 #ffffff。
package com.cd.administrator.mytopbar;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class TopBar extends RelativeLayout {
private Button leftButton, rightButton;
private TextView tvTitle;
private int leftTextColor, rightTextColor, titleTextColor;
private Drawable leftBackground, rightBackground;
private String leftText, rightText, titleText;
private float titleTextSize;
private topBarClickListener listener;
/** 對外暴露的點擊回呼介面 */
public interface topBarClickListener {
void leftClick();
void rightClick();
}
public void setOnTopBarClickListener(topBarClickListener listener) {
this.listener = listener;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public TopBar(Context context, AttributeSet attrs) {
super(context, attrs);
// 1. 取出 XML 中宣告的自定義屬性
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
leftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, 0);
leftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
leftText = ta.getString(R.styleable.TopBar_leftText);
rightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
rightBackground = ta.getDrawable(R.styleable.TopBar_rightBackground);
rightText = ta.getString(R.styleable.TopBar_rightText);
titleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, 0);
titleTextSize = ta.getDimension(R.styleable.TopBar_titleTextSize, 0);
titleText = ta.getString(R.styleable.TopBar_titleText);
ta.recycle(); // 2. 用完務必回收
// 3. 建立子 View 並套用屬性
leftButton = new Button(context);
rightButton = new Button(context);
tvTitle = new TextView(context);
leftButton.setTextColor(leftTextColor);
leftButton.setBackground(leftBackground);
leftButton.setText(leftText);
rightButton.setTextColor(rightTextColor);
rightButton.setBackground(rightBackground);
rightButton.setText(rightText);
tvTitle.setTextColor(titleTextColor);
tvTitle.setTextSize(titleTextSize);
tvTitle.setText(titleText);
tvTitle.setGravity(Gravity.CENTER);
setBackgroundColor(0xf59563);
// 4. 用 LayoutParams 定位:左右靠邊、標題居中
LayoutParams leftParams = new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
addView(leftButton, leftParams);
LayoutParams rightParams = new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
addView(rightButton, rightParams);
LayoutParams titleParams = new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
titleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
addView(tvTitle, titleParams);
// 5. 把內部點擊事件轉發給外部
leftButton.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
if (listener != null) listener.leftClick();
}
});
rightButton.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
if (listener != null) listener.rightClick();
}
});
}
}
這裡有個關鍵:根元素必須加上 xmlns:custom="https://schemas.android.com/apk/res-auto",否則自定義屬性無法解析。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:custom="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.cd.administrator.mytopbar.TopBar
android:id="@+id/topBar"
android:layout_width="match_parent"
android:layout_height="40dp"
custom:leftBackground="@drawable/blue"
custom:leftText="Back"
custom:leftTextColor="#ffffff"
custom:rightBackground="@drawable/blue"
custom:rightText="More"
custom:rightTextColor="#ffffff"
custom:titleTextColor="#121212"
custom:titleTextSize="15sp"
custom:titleText="自定義標題" />
</RelativeLayout>
package com.cd.administrator.mytopbar;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TopBar topBar = (TopBar) findViewById(R.id.topBar);
topBar.setOnTopBarClickListener(new TopBar.topBarClickListener() {
@Override
public void leftClick() {
Toast.makeText(MainActivity.this, "cd--left", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void rightClick() {
Toast.makeText(MainActivity.this, "cd--right", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
declare-styleable 宣告屬性,並在 name 屬性標籤上與控件類名保持一致。AttributeSet 的建構子中透過 obtainStyledAttributes 讀取,用完呼叫 recycle()。xmlns:custom="https://schemas.android.com/apk/res-auto"。進階一點的做法,還可以把 setBackgroundColor(0xf59563) 這種寫死的顏色也抽成 custom:background 屬性,並提供 setter 方法以便在程式碼中動態修改標題——這樣控件的可複用性會更高。
HandlerThread 源碼分析:讓子線程複用成為可能
我們都知道,在 Android 中執行耗時操作時需要另開子線程,任務結束後線程會自動銷毀。想象一下:如果項目裡要頻繁執行耗時任務,每次都開線程、用完又銷毀,無疑會帶來可觀
Android 利用 Gradle 實現 App 多環境分離
在 Android 專案中,測試環境與正式環境通常需要同時存在。若每次切換都要重新打包、反覆覆蓋安裝,不僅影響開發效率,也容易造成版本混淆。本文將說明如何透過 Gradl
SD 卡壞了怎麼辦?先別急著格式化,資料還有救
學習、工作、拍照,SD 卡幾乎無所不在。它容量可觀,卻 also 相當脆弱——一旦罷工,往往欲哭無淚。 面對讀不到的 SD 卡,第一反應通常是格式化,但這恰恰是資料徹底消
Android 自定義 View(一):初體驗
對 Android 開發者而言,自定義控制項是一項必備技能,但對許多人來說並不容易。工作時難免遇到需要自訂的效果,若你不會,內心難免有挫敗感。接下來我會寫一系列文章,和大