編輯:關於 Android 開發
日常開發中,一些看似瑣碎的控件問題往往最耗時間。本文整理了八個實用技巧,從日期輸入的驗證難題、TextView 的富文本呈現,到版面效能的優化,都是可以直接抄進專案的做法。
讓使用者輸入日期,最麻煩的其實是驗證——要擋掉 2 月 30 日、要處理各種格式。與其跟輸入法纏鬥,不如換個思路:用 Button 搭配 EditText 的背景,讓它看起來像輸入框,點下去直接跳出日期選擇器。
<Button
android:id="@+id/details_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/edit_text"
android:gravity="center"
android:text="輸入日期"
android:textColor="@android:color/holo_red_light" />
@android:drawable/edit_text 就是系統內建的 EditText 背景,所以視覺上完全看不出差別。接著在 Java 端處理點擊:
private int mYear;
private int mMonth;
private int mDay;
private OnDateSetListener mDateSetListener;
private Button mDateButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mDateButton.setText(getString(R.string.picked_date_format,
monthOfYear, dayOfMonth, year));
}
};
mDateButton = (Button) findViewById(R.id.details_date);
mDateButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDatePickerDialog();
}
});
}
private void showDatePickerDialog() {
new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay).show();
}
為什麼不直接替 EditText 掛點擊事件?因為 Button 的文字無法被使用者修改,安全性更高。當然你也可以用 TextWatcher 即時驗證輸入,只是那會花費更多程式碼。另外,直接沿用系統的 edit_text 背景與 DatePickerDialog,能讓介面自然貼合裝置本身的風格。

像推文那樣——黑色文字、藍色標籤、還有一部分可以點擊開啟連結——看起來像自訂控件,其實一個 TextView 就足夠。
<TextView
android:id="@+id/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="18sp" />
<TextView
android:id="@+id/text_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/hello_world"
android:layout_marginTop="4dp"
android:text="我感覺我要喝點水,可你的嘴將我的嘴堵住"
android:textSize="18sp" />
public class MainActivity extends AppCompatActivity {
TextView helloWorldText;
TextView textTwo;
String textLink = "visit Sina Home";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 加入可點擊的超連結
helloWorldText = (TextView) findViewById(R.id.hello_world);
helloWorldText.setText(Html.fromHtml(textLink));
helloWorldText.setMovementMethod(LinkMovementMethod.getInstance());
// 局部改變背景色與前景色
textTwo = (TextView) findViewById(R.id.text_2);
Spannable spannable = new SpannableString(textTwo.getText());
spannable.setSpan(new BackgroundColorSpan(Color.BLUE), 2, 5, 0);
int index = textTwo.getText().toString().indexOf(",");
spannable.setSpan(new ForegroundColorSpan(Color.YELLOW),
index, textTwo.getText().length(), 0);
textTwo.setText(spannable);
}
}
關鍵是 setMovementMethod(LinkMovementMethod.getInstance()),少了這一句連結無法點擊。而 Spannable 系列則讓你能針對任意字元區間套用顏色、字型、大小等樣式。


想要那種數位時鐘的七段顯示器效果,做法是自訂一個 TextView,把字型換成 LED 風格:
public class LedTextView extends TextView {
private static final String FONTS_FOLDER = "fonts";
private static final String FONT_DIGITAL_7 =
FONTS_FOLDER + File.separator + "digital-7.ttf";
public LedTextView(Context context) {
super(context);
init(context);
}
public LedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public LedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
AssetManager assets = context.getAssets();
final Typeface font = Typeface.createFromAsset(assets, FONT_DIGITAL_7);
setTypeface(font);
}
}
版面中放兩個 LedTextView,一個顯示半透明的「88:88:88」作為未亮起的底色,一個顯示實際時間疊在上面:
<merge xmlns:android="https://schemas.android.com/apk/res/android">
<com.manning.androidhacks.hack011.view.ledtextview
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="88:88:88"
android:textColor="#3300ff00"
android:textSize="80sp" />
<com.manning.androidhacks.hack011.view.ledtextview
android:id="@+id/main_clock_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#00ff00"
android:textSize="80sp" />
</merge>
Activity 中每 500 毫秒刷新一次:
public class MainActivity extends Activity {
private static final String DATE_FORMAT = "%02d:%02d:%02d";
private static final int REFRESH_DELAY = 500;
private final Handler mHandler = new Handler();
private final Runnable mTimeRefresher = new Runnable() {
@Override
public void run() {
final Date d = new Date();
mTextView.setText(String.format(DATE_FORMAT,
d.getHours(), d.getMinutes(), d.getSeconds()));
mHandler.postDelayed(this, REFRESH_DELAY);
}
};
private TextView mTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.main_clock_time);
}
@Override
protected void onResume() {
super.onResume();
mHandler.post(mTimeRefresher);
}
@Override
protected void onStop() {
super.onStop();
mHandler.removeCallbacks(mTimeRefresher);
}
}
這裡的 %02d 值得解釋一下:2 代表最小寬度,不足兩位時前方補 0。所以 printf("%02d", 3) 得到「03」;而 printf("%02d", 1234) 仍是「1234」,不會被截斷。另外別忘了在 onStop 中移除 callback,否則會造成記憶體洩漏。
這題沒什麼玄機,寫一個 shape drawable 指定給背景即可:
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#AAAAAA" />
<corners android:radius="15dp" />
</shape>
如果你在 onCreate 裡直接呼叫 getWidth() 與 getHeight(),拿到的會是 0。原因在於版面繪製分成 measure 與 layout 兩個階段:先量測寬高,再決定擺放位置。而 layout 發生在 onCreate 之後,此時控件尺寸尚未確定。
解法是使用 View 的 post() 方法,把 Runnable 丟進 UI 執行緒的訊息佇列,等 layout 完成後再執行:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.main_clock_time);
Log.d("crx", "before post: width=" + mTextView.getWidth()
+ ", height=" + mTextView.getHeight());
mTextView.post(new Runnable() {
@Override
public void run() {
Log.d("crx", "after post: width=" + mTextView.getWidth()
+ ", height=" + mTextView.getHeight());
}
});
}
執行結果會清楚顯示:post 之前是 0,post 之後才是真實數值。

要讓影片在手機旋轉時自動跟著調整,思路是這樣:版面中放一個佔滿整個螢幕但平時隱藏的 VideoView,再放一個佔位用的 View 標記出「直立時影片應該在哪裡」。
接著在 Manifest 中為該 Activity 加上 android:configChanges="orientation",這樣旋轉時就不會重建 Activity,而是回呼 onConfigurationChanged():
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
switch (getResources().getConfiguration().orientation) {
case Configuration.ORIENTATION_LANDSCAPE: {
// 橫屏:讓影片填滿整個父容器
mPortraitContent.setVisibility(View.GONE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
mVideoView.setLayoutParams(params);
break;
}
case Configuration.ORIENTATION_PORTRAIT:
default: {
// 直立:沿用佔位 View 的位置與尺寸
mPortraitContent.setVisibility(View.VISIBLE);
int[] locationArray = new int[2];
mPortraitPosition.getLocationOnScreen(locationArray);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
mPortraitPosition.getWidth(), mPortraitPosition.getHeight());
params.leftMargin = locationArray[0];
params.topMargin = locationArray[1];
mVideoView.setLayoutParams(params);
break;
}
}
}
這樣一來,直立時影片乖乖待在版面配置的位置,橫屏時才放大填滿,視覺切換會順很多。
Android SDK 附帶的 Hierarchy Viewer 能清楚呈現版面的層級與複雜度(真機可能無法使用,建議搭配模擬器)。檢視一個預設專案會發現,層級樹中有一大塊是 ActionBar,而它並不在你的版面檔裡——那是主題自帶的。

在 res/values 下新增一個自訂主題,把標題列拿掉:
<resources>
<style name="Theme.NoBackground" parent="android:Theme">
<item name="android:windowNoTitle">true</item>
</style>
</resources>
再用 Hierarchy Viewer 看一次。

可以明顯看到樹的深度少了一層,分支也變少了,真機上的啟動速度確實有改善。
至於層級樹中的 DecorView 與 FrameLayout 從何而來?FrameLayout 是 setContentView() 執行時產生的,DecorView 則是整棵樹的根節點。預設情況下,FrameLayout 會填滿整個螢幕並帶有預設背景色,DecorView 則持有整個螢幕的背景。如果你確定介面使用自訂背景,這道預設繪製就是純粹的浪費。只要再補一行即可關掉:
<resources>
<style name="Theme.NoBackground" parent="android:Theme">
<item name="android:windowNoTitle">true</item>
<item name="android:windowBackground">@null</item>
</style>
</resources>
Toast 預設出現在我們最熟悉的位置:螢幕下方正中。若要改,用 setGravity():
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); // 左上角
想要自訂樣式,先寫好版面:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#DAAA"
android:orientation="horizontal"
android:padding="8dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:src="@drawable/droid" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF" />
</LinearLayout>
然後在程式碼中把它塞進 Toast:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
需要注意的是,自訂 Toast 的版面中不宜放置可互動的控件,因為 Toast 本身無法接收觸摸事件。若真的有互動需求,應該改用 Dialog 或 PopupWindow。
FFmpeg 使用手冊:ffplay 常用命令與可視化分析技巧
ffplay 從哪裡來 編譯 FFmpeg 源碼時,只要系統中裝有 SDL-1.2,ffplay 就會被一併編譯出來;若缺少 SDL-1.2 或版本不符,則不會生成該可執
電信網絡拓撲自動佈局實踐:從 AutoLayout、ForceLayout 到自訂 ShapeLayout
海量節點面前,手工擺放並不現實 電信網絡拓撲圖的規模往往以千計。節點之間存在多層級的歸屬關係,連線縱橫交錯,若靠工程師逐個拖拽定位,不僅耗時驚人,成果也難以複製。自動佈局
Android 好用的日誌工具 KLog 使用詳解
在 Android 開發與調試過程中,打印日誌的頻率非常高。一個好用的 Log 工具能幫你省下大量排查時間。KLog 就是這樣一款開源庫,靈感來自 Logger,目標是
Genymotion 模擬器在 Android 開發中的配置方式
Genymotion 簡介 Genymotion 是一套 Android 虛擬環境工具,常用於開發、測試與展示。它通常運行在 VirtualBox 之上,提供比部分內建模