編輯:關於 Android 開發
本篇要處理的是好幾個常一起出現的知識點:Intent 與 Bundle 在頁面跳轉中的用法、ListView 與各種 Adapter 的搭配,順便把 RelativeLayout 一起講清楚。由於內容較多,文中不會貼出全部實驗代碼,只保留關鍵片段。
布局檔裡先寫一個 ListView 即可,這樣得到的是一個空列表,資料稍後在 java 檔中填入,所以 id 一定要設。

取得 ListView 之後,透過 Adapter 為它填充資料。最常見的是 ArrayAdapter 與 SimpleAdapter;當列表結構變複雜時,實務上多半會改用自定義 Adapter。Adapter 的角色,就是把資料處理成視圖能呈現的樣子。
最簡單的一種,建立時需要三個參數:
Context:代表存取整個應用的接口,幾乎建立任何控件都要傳它。
textViewResourceId:一個資源 ID,對應的 layout 中的 TextView 將作為列表項控件。
資料陣列或 List:負責為各列表項提供內容。

建立好之後呼叫 ListView 的 setAdapter() 就完成了。這裡有個容易忽略的限制:textViewResourceId 指向的 layout 裡只能有一個 TextView,連 LinearLayout 之類的布局節點都不能放,否則會直接報錯。
ArrayAdapter 只能顯示文字,遇到聯絡人清單這種「頭像 + 名稱 + 號碼」的複合結構就無力了。SimpleAdapter 能勝任,但需要自己設計樣式。
建立 SimpleAdapter 需要五個參數,第一個一樣是 Context,其餘四個分別是:
第二個:List 型別(元素為 Map),每個 Map 產生一個列表項。
第三個:指定列表項外觀的布局 ID。
第四個:String 陣列,決定要從 Map 中取出哪些 key 對應的 value。
第五個:int 陣列,決定這些值要填進哪些控件。
先準備資料,這裡用一個 Map 模擬圖書清單,放書名與價格兩個 key:

接著建立 SimpleAdapter:

同樣用 setAdapter() 掛上去。R.layout.item 的內容如下:

一個 LinearLayout 裡含兩個 TextView,分別顯示書名與價格。第四參數的 String 陣列與 Map 的兩個 key 一一對應,第五參數的 int 陣列則與兩個 TextView 的 id 一一對應,順序不能錯開。


長按事件有返回值。兩個方法的參數中都有 int i 與 long l:i 是該項在列表中的位置,l 是該項的 id。在 ArrayAdapter 與 SimpleAdapter 中兩者相等;但在 CursorAdapter 中,l 指的是資料在資料庫裡的實際 id,兩者就會不同。
直覺做法是重新 new 一個 SimpleAdapter,但這並非必要。SimpleAdapter 提供了 notifyDataSetChanged(),當來源 List 變動後呼叫它即可刷新。
要特別注意的是,List 不能指向新的記憶體位址——寫 list = new ArrayList<>(); 是不會生效的,只能用 remove()、add() 等方法去改動原本的資料集。

錯誤寫法:

正式上架的應用幾乎都不會有調試時那條標題欄。做法是改主題的 parent。Android Studio 預設的主題定義如下:


把 parent 換成不帶 ActionBar 的版本即可:

難點在於如何知道星星目前是空心還是實心。最簡潔的做法是用 tag:初始化時設為 0 代表空心;點擊後若 tag 為 0,換成實心圖並把 tag 設為 1;若 tag 已是 1,換回空心並重設為 0。建議在 java 檔中設定 tag,而不是寫在 xml 裡。
RelativeLayout 是僅次於 LinearLayout 的常用布局,比線性布局靈活:不必層層嵌套,每個子元素都能指定自己相對其他元素或父容器的位置,代價是必須透過 id 來參照。
它依子元素之間的位置關係完成布局,layout_below、layout_above 這類屬性都會生效。要注意的是,被參照的 id 必須在使用之前就已定義,否則會拋出異常。
組件之間的位置關係
layout_above 放在指定 id 組件的上方;layout_below 放在下方;layout_toLeftOf 放在左方;layout_toRightOf 放在右方。
與指定組件的對齊關係
layout_alignBaseline 基線對齊;layout_alignTop 頂部對齊;layout_alignBottom 底部對齊;layout_alignLeft 左緣對齊;layout_alignRight 右緣對齊。
與父容器的對齊關係
layout_centerHorizontal 水平居中;layout_centerVertical 垂直居中;layout_centerInParent 置於父容器正中央。
ArrayAdapter 與 SimpleAdapter 都有天花板。若列表項需要特殊樣式,或某個子控件要掛監聽器,就只能自己寫。強烈建議從一開始就養成寫自定義 Adapter 的習慣,只在真的很簡單的場合才用前兩者。
自定義 Adapter 需繼承 BaseAdapter,並實作四個方法:

getCount() 回傳資料項數量;getItem(int i) 取得某一項資料;getItemId(int i) 取得該項位置;getView(int i, View view, ViewGroup viewGroup) 決定該項的外觀,是最關鍵的一個。
資料來源通常是一個 List。以圖書列表為例,先替列表項建立一個 Book 類別,再把 List 傳進 Adapter:


三個參數的意義:i 是目前在載入第幾項;viewGroup 是列表項的父視圖,調整寬高時用得到;view 是列表項本身的視圖,要為它載入布局並填入內容。

基本寫法
每次滾進一項就重新 inflate 一次布局。問題很明顯:ListView 滾出一項的同時會滾進一項,那個被回收的 view 其實可以重複使用,只是內容是舊的,改掉再回傳就好,不必重新載入布局。
改進版

這樣已能省下重複載入的開銷。但每次都要 findViewById 仍然煩瑣,控件一多效能也會受影響。
改進版 2.0:加上 ViewHolder

用 setTag 把 ViewHolder 掛在 convertView 上,下次直接取出,就不必再走 findViewById。這是自定義 Adapter 的標準收尾手法。



本次實驗做一個兩頁的通訊錄。首頁呈現清單:

點擊任一項進入詳情頁:

布局要求
清單項為「圓圈 + 姓名」,兩者皆垂直居中;圓圈內是姓名首字母,白色、置中,姓名為黑色。圓圈顏色自訂,建議用較深的色系,否則白字會看不清。
詳情頁頂部背景色由資料自帶,佔整個畫面的三分之一。返回圖示在左上角,姓名在左下角,星標在右下角,彼此間距自行拿捏。要特別注意:返回圖示與姓名左對齊,姓名與星標底邊對齊。

中部「手機」等資訊使用 #D5000000,較淺的說明文字用 #8A000000。號碼下方有一條 #1E000000 的分割線,聊天圖示左側也有一條同色分割線,其高度需與圖示一致並垂直居中。

底部為操作列表。

兩個頁面都要去掉標題欄。
功能要求
點擊聯絡人跳轉詳情頁;長按彈出對話框詢問是否刪除,確認則刪除、取消則關閉,對話框中的人名要是被長按的那一位。

詳情頁點返回圖示回上一層,點星標切換空心與實心。
清單項布局用 LinearLayout 包兩個 TextView,第一個的背景是在 drawable 中建立的 shape,用 size 屬性畫出圓形:

資料部分另外建一個 java 類別封裝,提供 get 與 set 方法。為每筆資料建立物件後加入 List,方便後續在頁面間傳遞。
SimpleAdapter 的資料來源是一組 Map,key 分別是首字母與姓名,分別塞進字元陣列與字串陣列,再以鍵值對形式加入 list:

單擊事件中處理頁面跳轉與傳值。由於要傳的是物件,Info 類別必須實作 Serializable,再把物件放進 Intent 的 extra;詳情頁則用 getSerializableExtra 取出。長按事件中彈出 AlertDialog 並處理刪除,因為用 List 模擬資料庫,所以要把 List 中對應的那筆一起移除。

刪除後呼叫 notifyDataSetChanged() 刷新清單。再次提醒:List 不可重新指向新的記憶體位址,只能用 remove()、add() 改動。
星標切換同樣靠 tag 判斷狀態:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.yanglh6.myapp3.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Start">
</ListView>
</RelativeLayout>
activity_info.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.yanglh6.myapp3.InfoActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@+id/Top"
android:layout_weight="1"
android:background="@color/colorPrimaryDark">
<Button
android:layout_width="50dp"
android:layout_height="50dp"
android:id="@+id/Back"
android:layout_marginStart="10dp"
android:background="@mipmap/back" />
<Button
android:layout_width="35dp"
android:layout_height="35dp"
android:id="@+id/star"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="25dp"
android:layout_marginEnd="20dp"
android:background="@mipmap/empty_star" />
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:id="@+id/Name"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:textSize="25sp"
android:layout_marginBottom="15dp"
android:layout_marginStart="20dp"
android:textColor="@color/white" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/telephone"
android:layout_marginStart="12dp"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:textColor="@color/telephoneNumber" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/info1"
android:layout_alignStart="@+id/telephone"
android:layout_below="@+id/telephone"
android:textSize="15sp"
android:layout_marginTop="8dp"
android:textColor="@color/telephone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/info2"
android:layout_alignBottom="@+id/info1"
android:layout_marginStart="10dp"
android:textSize="15sp"
android:layout_toEndOf="@+id/info1"
android:textColor="@color/telephone" />
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:id="@+id/chat"
android:layout_alignParentEnd="true"
android:layout_alignTop="@+id/telephone"
android:layout_marginEnd="15dp"
android:layout_marginTop="8dp"
android:background="@mipmap/chat" />
<View
android:layout_width="2dp"
android:layout_height="40dp"
android:layout_alignTop="@+id/chat"
android:layout_marginEnd="18dp"
android:layout_toStartOf="@+id/chat"
android:background="@color/line" />
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:id="@+id/line"
android:layout_alignStart="@+id/info1"
android:layout_below="@+id/info1"
android:layout_marginTop="10dp"
android:background="@color/line" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/more"
android:layout_below="@+id/line"></ListView>
<View
android:layout_width="match_parent"
android:layout_height="18dp"
android:layout_below="@+id/more"
android:background="@color/line" />
</RelativeLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview"></ListView>
</LinearLayout>
</LinearLayout>
info.xml(more.xml 內容相同)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/cycle"
android:textSize="18sp"
android:textColor="@color/white"
android:background="@drawable/shape"
android:gravity="center"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/name"
android:textSize="20sp"
android:layout_weight="1"
android:textColor="@color/black"
android:padding="15dp" />
</LinearLayout>
MainActivity.java
package com.example.yanglh6.myapp3;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.os.Bundle;
import android.view.View;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<Map<String, Object>> data = new ArrayList<>();
/* 為每一項數據創建一個對象,並添加在 List 中 */
final List<Info> Infos = new ArrayList<Info>() {{
add(new Info("Aaron", "17715523654", "手機", "江蘇蘇州電信", "#BB4C3B"));
add(new Info("Elvis", "18825653224", "手機", "廣東揭陽移動", "#c48d30"));
add(new Info("David", "15052116654", "手機", "江蘇無錫移動", "#4469b0"));
add(new Info("Edwin", "18854211875", "手機", "山東青島移動", "#20A17B"));
add(new Info("Frank", "13955188541", "手機", "安徽合肥移動", "#BB4C3B"));
add(new Info("Joshua", "13621574410", "手機", "江蘇蘇州移動", "#c48d30"));
add(new Info("Ivan", "15684122771", "手機", "山東煙台聯通", "#4469b0"));
add(new Info("Mark", "17765213579", "手機", "廣東珠海電信", "#20A17B"));
add(new Info("Joseph", "13315466578", "手機", "河北石家莊電信", "#BB4C3B"));
add(new Info("Phoebe", "17895466428", "手機", "山東東營移動", "#c48d30"));
}};
char[] cycle = new char[Infos.size()];
for (int i = 0; i < Infos.size(); i++) {
cycle[i] = Infos.get(i).getcycle();
}
String[] name = new String[Infos.size()];
for (int i = 0; i < Infos.size(); i++) {
name[i] = Infos.get(i).getName();
}
for (int i = 0; i < Infos.size(); i++) {
Map<String, Object> temp = new LinkedHashMap<>();
temp.put("cycle", cycle[i]);
temp.put("name", name[i]);
data.add(temp);
}
/* ListView 單擊事件 */
ListView listView = (ListView) findViewById(R.id.Start);
final SimpleAdapter simpleAdapter = new SimpleAdapter(this, data, R.layout.info,
new String[]{"cycle", "name"},
new int[]{R.id.cycle, R.id.name});
listView.setAdapter(simpleAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(MainActivity.this, InfoActivity.class);
Info temp = Infos.get(i);
intent.putExtra("Info", temp);
startActivity(intent);
}
});
/* ListView 長按事件 */
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
final int position, long id) {
AlertDialog.Builder message = new AlertDialog.Builder(MainActivity.this);
message.setTitle("刪除聯系人");
message.setMessage("確定刪除聯系人" + Infos.get(position).getName());
message.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
Infos.remove(position);
data.remove(position);
simpleAdapter.notifyDataSetChanged();
}
});
message.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
message.create().show();
return true;
}
});
}
}
Info.java
package com.example.yanglh6.myapp3;
import java.io.Serializable;
/* 存儲相應的數據 */
public class Info implements Serializable {
public Info(String name, String tel, String info1, String from, String background) {
this.background = background;
this.info1 = info1;
this.from = from;
this.name = name;
this.tel = tel;
}
public String getBackground() { return background; }
public void setBackground(String background) { this.background = background; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getFrom() { return from; }
public void setFrom(String from) { this.from = from; }
public String getTel() { return tel; }
public void setTel(String tel) { this.tel = tel; }
public String getinfo1() { return info1; }
public void setinfo1(String info1) { this.info1 = info1; }
/* 取姓名首字母,小寫字母則轉為大寫 */
public char getcycle() {
char first = name.charAt(0);
if (first >= 97 && first <= 122) {
first -= 32;
}
return first;
}
private String background;
private String info1;
private String from;
private String name;
private String tel;
}
InfoActivity.java
package com.example.yanglh6.myapp3;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Button;
import android.widget.ListView;
public class InfoActivity extends AppCompatActivity {
private boolean tag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
Info p = (Info) getIntent().getSerializableExtra("Info");
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.Top);
relativeLayout.setBackgroundColor(Color.parseColor(p.getBackground()));
Button back = (Button) findViewById(R.id.Back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
((TextView) findViewById(R.id.info1)).setText(p.getinfo1());
((TextView) findViewById(R.id.info2)).setText(p.getFrom());
((TextView) findViewById(R.id.Name)).setText(p.getName());
((TextView) findViewById(R.id.telephone)).setText(p.getTel());
String[] operations1 = new String[]{"更多資料"};
ArrayAdapter<String> arrayAdapter1 =
new ArrayAdapter<>(this, R.layout.more, operations1);
ListView listView1 = (ListView) findViewById(R.id.more);
listView1.setAdapter(arrayAdapter1);
String[] operations2 = new String[]{"編輯聯系人", "分享聯系人", "加入黑名單", "刪除聯系人"};
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<>(this, R.layout.more, operations2);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(arrayAdapter);
/* 星星的切換 */
final Button star = (Button) findViewById(R.id.star);
star.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!tag) {
star.setBackground(getDrawable(R.mipmap.full_star));
tag = true;
} else {
star.setBackground(getDrawable(R.mipmap.empty_star));
tag = false;
}
}
});
}
}



實驗環境:Windows 10、Android Studio 2.2.1、模擬器 Nexus_5X、API 23。貼代碼時因插入框寬度限制,部分格式做了整理。
Android 移除標題欄的三種做法
Android 移除標題欄的三種做法 開發全屏或自訂頂欄的應用時,第一步通常就是把系統預設的標題欄拿掉。以下整理三種做法,適用範圍各有不同。 做法一:在程式碼中實作 //
基於微信開放平台 v3 SDK 接入微信支付的填坑全記錄
接觸微信支付之前,就聽說這是個「坑」,心裡早有了準備。原以為自己會跳進去爬不出來,沒想到最終還是把它填平了。調用成功的那一刻,我感覺公司所有同事都變得可愛起來,隔著北京的
在 Eclipse 中安裝配置 Genymotion 模擬器的問題排查與解決
由於 Android ADT 自帶的原生模擬器運行速度實在太慢,很多人會選擇安裝第三方模擬器 Genymotion。不過在安裝過程中難免會遇到各種各樣的問題,本文就結合實
在Android(Linux)上即時抓取串口數據的實踐之路
在Android(Linux)上即時抓取串口數據的實踐之路 早年在做WinCE車載方案時,我曾寫過一個叫TraceMonitor的小工具,用來顯示WinCE系統上應用程式