編輯:Android 開發實例
Android 把圖片、字串、色彩、尺寸、版面、動畫等外部檔案統稱為「資源」。資源與程式碼分離,是 Android 能支援多語言、多螢幕的基礎,也是開發時必須先建立的觀念。
與 src 並列的 assets 與 res 都用來放資源,但性質完全不同:
取用 res 資源時,一般透過 getResources() 取得 Resources 物件,再呼叫對應的方法(getColor、getString、getDrawable、getDimension 等)。
支援 #RGB、#ARGB、#RRGGBB、#AARRGGBB 四種寫法,以 Resources 的 getColor() 讀取。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#FFFFFF</color>
<color name="black">#000000</color>
</resources>
把所有顯示文字集中管理,是支援多語系的前提:只要再建立 values-en、values-ja 等目錄放入同名檔案,系統就會依裝置語言自動挑選。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ResrouseTestActivity!</string>
<string name="app_name">ResrouseTest</string>
</resources>
建議使用 PNG 格式;其他格式容易出現相容問題,GIF 並不被直接支援,若需播放 GIF 得改用 Movie 類別。此目錄也可放 XML 描述檔,常用於自訂元件的外觀定義(如 shape、selector)。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="solid_red">#FF0000</drawable>
</resources>
它的用途是定義填滿元件背景的色值,使用方式與 drawable 下的圖片相同。實務上直接用顏色資源即可,這種寫法的額外好處有限。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="dimen_name">2px</dimen>
<dimen name="dimen_px">5px</dimen>
<dimen name="dimen_pt">3pt</dimen>
<dimen name="dimen_dp">3dp</dimen>
</resources>
寫法與 color、string 相同,差別在單位。px 是實體像素,在不同解析度螢幕上大小不一;dp(密度-independent pixel)會依螢幕密度自動換算,是跨裝置版面首選;sp 則用於文字,會一併反映使用者設定的字級。
當圖片作為 View 的 background 時,會隨 View 尺寸自動拉伸與收縮;而作為 ImageView 的 src 時則不隨 View 變化,只依自身尺寸顯示部分或全部。Nine-patch(.9.png)透過在圖片四周加上一像素的拉伸區標記,讓開發者指定哪幾段可以拉伸、哪一段固定,避免圓角或邊框被拉壞。
菜單可用程式碼建立,也可寫在資源中由 MenuInflater 擴充:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="https://schemas.android.com/apk/res/android">
<item android:id="@+id/previous"
android:title="@string/previous"
android:enabled="false"
android:icon="@android:drawable/ic_media_previous"/>
<item android:id="@+id/play_pause"
android:title="@string/play"
android:icon="@android:drawable/ic_media_play"/>
<item android:id="@+id/next"
android:title="@string/next"
android:icon="@android:drawable/ic_menu_next"/>
</menu>
就是描述畫面上各 View 排列與嵌套的 XML。把畫面結構寫在這裡,Activity 只需 setContentView() 一行即可掛載,這正是關注點分離的實踐。
樣式(style)針對單一 View 的外觀,把重複設定的屬性群組化,可透過 parent 繼承既有樣式:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="SpecialText" parent="@style/Text">
<item name="android:textSize">18sp</item>
<item name="android:textColor">#008</item>
</style>
</resources>
主題(theme)則針對整個 Activity 或應用程式,在 AndroidManifest.xml 的 <application> 或 <activity> 元素上指定。兩者的關鍵差異是:主題無法套用到單一 View 上。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomTheme">
<item name="android:windowNoTitle">true</item>
<item name="windowFrame">@drawable/screen_frame</item>
<item name="windowBackground">@drawable/screen_background_white</item>
<item name="panelForegroundColor">#FF000000</item>
<item name="panelBackgroundColor">#FFFFFFFF</item>
<item name="panelTextColor">?panelForegroundColor</item>
<item name="panelTextSize">14</item>
<item name="menuItemTextColor">?panelTextColor</item>
<item name="menuItemTextSize">?panelTextSize</item>
</style>
</resources>
動畫資源有兩種。第一種是 tween 動畫,對圖片做 translate、scale、rotate、alpha 四種變換,並可設定播放特性;第二種是逐幀動畫(frame animation),依序播放設定的圖片資源。
<set xmlns:android="https://schemas.android.com/apk/res/android">
<translate android:interpolator="@android:anim/accelerate_interpolator"
android:fromXDelta="0" android:toXDelta="200"
android:fromYDelta="0" android:toYDelta="180"
android:duration="2000" />
<scale android:interpolator="@android:anim/accelerate_interpolator"
android:fromXScale="1.0" android:toXScale="2.0"
android:fromYScale="1.0" android:toYScale="2.0"
android:pivotX="150%" android:pivotY="150%"
android:duration="2000" />
<alpha android:fromAlpha="1.0" android:toAlpha="1.0"
android:duration="@android:integer/config_mediumAnimTime" />
<rotate ... />
<!-- Interpolator 可使用其子類與屬性定義節奏:先快後慢、先慢後快等 -->
</set>
逐幀動畫則用 animation-list 描述每一幀的圖片與停留時間,oneshot 設為 true 時只播放一次:
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
android:oneshot="true">
<item android:drawable="@drawable/rocket_thrust1" android:duration="200" />
<item android:drawable="@drawable/rocket_thrust2" android:duration="200" />
<item android:drawable="@drawable/rocket_thrust3" android:duration="200" />
</animation-list>
以下範例以一個 ListActivity 作為總入口,點選各項進入對應的資源測試頁。
package com.amaker.test;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.amaker.ch03.color.TestColorActivity;
import com.amaker.ch03.dimen.TestDimensionActivity;
import com.amaker.ch03.drawable.TestBitmapActivity;
import com.amaker.ch03.layout.TestLayoutActivity;
import com.amaker.ch03.menu.TestMenuActivity;
import com.amaker.ch03.string.TestStringActivity;
import com.amaker.ch03.xml.TestXmlActivity;
public class MainActivity extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 菜單項陣列
String[] items = {"Test Color", "Test String", "Test Dimension",
"Test XML", "Test Bitmap", "Test Menu", "Test Layout"};
// 將陣列設為 ListView 的列表項
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
getListView().setTextFilterEnabled(true);
}
// 回應列表項的點擊事件
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = null;
switch (position) {
case 0: intent = new Intent(MainActivity.this, TestColorActivity.class); break;
case 1: intent = new Intent(MainActivity.this, TestStringActivity.class); break;
case 2: intent = new Intent(MainActivity.this, TestDimensionActivity.class); break;
case 3: intent = new Intent(MainActivity.this, TestXmlActivity.class); break;
case 4: intent = new Intent(MainActivity.this, TestBitmapActivity.class); break;
case 5: intent = new Intent(MainActivity.this, TestMenuActivity.class); break;
case 6: intent = new Intent(MainActivity.this, TestLayoutActivity.class); break;
}
if (intent != null) {
startActivity(intent);
}
}
}
package com.amaker.ch03.color;
import android.app.Activity;
import android.os.Bundle;
import com.amaker.test.R;
public class TestColorActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_color);
// 引用顏色資源,設定背景為紅色
getWindow().setBackgroundDrawableResource(R.color.red_bg);
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red_bg">#f00</color>
<color name="blue_text">#0000ff</color>
</resources>
package com.amaker.ch03.dimen;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.Button;
import com.amaker.test.R;
public class TestDimensionActivity extends Activity {
private Button myButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_dimen);
myButton = (Button)findViewById(R.id.Button01);
Resources r = getResources();
float btn_h = r.getDimension(R.dimen.btn_height);
float btn_w = r.getDimension(R.dimen.btn_width);
myButton.setHeight((int)btn_h);
myButton.setWidth((int)btn_w);
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="text_width">150px</dimen>
<dimen name="text_height">100px</dimen>
<dimen name="btn_width">30mm</dimen>
<dimen name="btn_height">10mm</dimen>
</resources>
package com.amaker.ch03.drawable;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import com.amaker.test.R;
public class TestBitmapActivity extends Activity {
private ImageView myImageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_bitmap);
myImageView = (ImageView)findViewById(R.id.bitmapImageView02);
Resources r = getResources();
Drawable d = r.getDrawable(R.drawable.moto);
myImageView.setImageDrawable(d);
}
}
package com.amaker.ch03.layout;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.amaker.test.R;
public class TestLayoutActivity extends Activity {
private TextView myTextView;
private EditText myEditText;
private Button myButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
myTextView = (TextView)findViewById(R.id.layoutTextView01);
myEditText = (EditText)findViewById(R.id.layoutEditText01);
myButton = (Button)findViewById(R.id.layoutButton01);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- 以上四個屬性分別是:命名空間、排列方向(垂直)、寬(填滿螢幕)、高(填滿螢幕)-->
<!-- 以下嵌套一個 TableLayout -->
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="測試Layout:"
android:id="@+id/layoutTextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/red_bg"/>
<!-- 以上五個屬性分別是:文字內容、元件 ID、寬(依內容)、高(依內容)、文字顏色(引用顏色資源)-->
<EditText
android:text=""
android:id="@+id/layoutEditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</TableRow>
<TableRow android:gravity="right">
<Button
android:text="Test"
android:id="@+id/layoutButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</TableRow>
</TableLayout>
</LinearLayout>
這段配置示範了資源交叉引用的威力:android:textColor="@color/red_bg" 直接指向 colors.xml 中的定義,而程式碼那側又能用同一個 R.color.red_bg 取用,同一份定義在兩處保持一致。
package com.amaker.ch03.menu;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.amaker.test.R;
public class TestMenuActivity extends Activity {
private MenuInflater mi;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_menu);
mi = new MenuInflater(this);
}
/* 建立菜單:從 XML 資源擴充 */
public boolean onCreateOptionsMenu(Menu menu) {
mi.inflate(R.menu.file_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about:
aboutAlert("本範例示範如何使用 XML 菜單資源來定義菜單!");
break;
case R.id.exit:
exitAlert("真的要退出嗎?");
break;
}
return true;
}
// 顯示對話框
private void exitAlert(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg)
.setCancelable(false)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
// 顯示對話框
private void aboutAlert(String msg) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(msg)
.setCancelable(false)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
對應的畫面配置:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="測試菜單資源"
android:id="@+id/menuTextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
package com.amaker.ch03.string;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.amaker.test.R;
public class TestStringActivity extends Activity {
private TextView myTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_string);
myTextView = (TextView)findViewById(R.id.myTextView02);
String str = getString(R.string.test_str2).toString();
myTextView.setText(str);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- 在 XML 中直接引用字串資源 -->
<TextView
android:text="@string/test_str1"
android:id="@+id/myTextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<!-- 這個空白的 TextView 由程式碼填入 -->
<TextView
android:text=""
android:id="@+id/myTextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
同一份字串有兩種取用路徑:XML 中用 @string/xxx 引用,程式碼中用 getString(R.string.xxx)。前者適合靜態文字,後者適合需要拼接或條件判斷的情境。
放在 res/xml 下的檔案不會被系統特殊處理,需要用 XmlResourceParser 自行走訪節點。以下範例讀取一份客戶資料 XML,把每個 customer 節點的屬性攤平成文字。
package com.amaker.ch03.xml;
import java.io.IOException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.amaker.test.R;
public class TestXmlActivity extends Activity {
private TextView myTextView;
private Button myButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_xml);
myTextView = (TextView)findViewById(R.id.xmlContentTextView01);
myButton = (Button)findViewById(R.id.xmltTestButton01);
myButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int counter = 0;
StringBuilder sb = new StringBuilder("");
Resources r = getResources();
XmlResourceParser xrp = r.getXml(R.xml.test);
try {
while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xrp.getEventType() == XmlResourceParser.START_TAG) {
String name = xrp.getName();
if (name.equals("customer")) {
counter++;
sb.append("第" + counter + "條客戶信息:" + "\n");
sb.append(xrp.getAttributeValue(0) + "\n");
sb.append(xrp.getAttributeValue(1) + "\n");
sb.append(xrp.getAttributeValue(2) + "\n");
sb.append(xrp.getAttributeValue(3) + "\n\n");
}
} else if (xrp.getEventType() == XmlPullParser.END_TAG) {
} else if (xrp.getEventType() == XmlPullParser.TEXT) {
}
xrp.next();
}
myTextView.setText(sb.toString());
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
解析 XML 屬於 I/O 操作,範例為了簡潔直接在主執行緒處理;實務上檔案稍大就應該移到背景執行緒,再以 Handler 回傳結果更新 TextView,避免造成畫面 ANR。
把資源外部化有三個直接好處:多語系只需新增 values-xx 目錄、多螢幕只需新增 drawable-land 或 layout-xlarge、外觀調整不必重新編譯程式碼。養成「不寫死字串與尺寸」的習慣,是 Android 開發最基本的紀律。此外,assets 與 res 的選擇判斷很簡單:需要系統幫你產生 ID、需要多語系與多螢幕自動切換的,放 res;只是要原封不動讀進來的檔案,放 assets。
Android 登入頁面:三機會驗證與按鈕禁用
許多 App 需要登入頁面來保護使用者資料。除了基本的帳號密碼輸入,也可以加入錯誤次數限制,提高安全性。 登入欄位設計 畫面中需要兩個 EditText,一個輸入使用者名
Android 登入畫面實作:輸入欄位、驗證與失敗鎖定
登入畫面幾乎是每個需要帳號的 App 都躲不掉的一關。使用者要在這裡輸入帳號與密碼,App 則負責把資料送出去驗證、處理錯誤、並且防止有心人士暴力猜密碼。本章就從零把這幾
Android Wear 計時器開發(一):為什麼不能照搬手機的設計思路
早在 2013 年 12 月,我曾寫過一系列文章,示範如何開發一款讓用戶在足球比賽中記錄停表時間的 App。等到 Android Wear 問世,把這樣的應用搬到智慧手錶
Android 進階:打造手機模擬信號示波器
前面我們簡單介紹過 Android 開發中 AudioRecord 與 AudioTrack 的用法,這次結合 SurfaceView,動手做一個 Android 版的手