Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android ApiDemo 圖形與視圖(三):從 LinearLayout 到 TableLayout 的布局實戰

編輯:初階開發

本篇延續 ApiDemo 中「Graphics and Views」的閱讀筆記,涵蓋第 37 到第 57 號範例。這一段的重心很明確:把布局從「寫死在 XML 裡」變成「可以動態操縱的對象」,並把 TableLayout 這個最容易被誤解的容器徹底拆解。建議搭配 ApiDemo 原始碼一起看,邊跑邊對照效果會快很多。

37. LinearLayout8:用選單即時改變排列方式

這個範例示範了一件很實用的事:布局寫好之後,仍然可以在執行期透過 OptionsMenu 改變 LinearLayout 的排列方向與對齊方式。

初始布局

外層是 FrameLayout,內層放一個 vertical 的 LinearLayout,裡面堆三個 TextView,各自套上 @drawable/box 背景,方便肉眼分辨每個子項的邊界。

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="30dip">

    <LinearLayout
        android:id="@+id/layout"
        android:orientation="vertical"
        android:background="@drawable/blue"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="30dip">

        <TextView android:background="@drawable/box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/linear_layout_8_c" />
        <TextView android:background="@drawable/box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/linear_layout_8_b" />
        <TextView android:background="@drawable/box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/linear_layout_8_c" />

    </LinearLayout>
</FrameLayout>

菜單回呼:onOptionsItemSelected

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case VERTICAL_ID:
        mLinearLayout.setOrientation(LinearLayout.VERTICAL);
        return true;
    case HORIZONTAL_ID:
        mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
        return true;

    case TOP_ID:
        mLinearLayout.setGravity(Gravity.TOP);
        return true;
    case MIDDLE_ID:
        mLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
        return true;
    case BOTTOM_ID:
        mLinearLayout.setGravity(Gravity.BOTTOM);
        return true;

    case LEFT_ID:
        mLinearLayout.setGravity(Gravity.LEFT);
        return true;
    case CENTER_ID:
        mLinearLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        return true;
    case RIGHT_ID:
        mLinearLayout.setGravity(Gravity.RIGHT);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

關鍵只有兩個 API:setOrientation() 決定子項是「由上往下」還是「由左往右」排列;setGravity() 決定這一整排內容在容器中被拉到哪個位置。要注意方向與重力必須成對思考——改成 horizontal 之後,原本負責垂直對齊的 TOP/BOTTOM 就不再是你想像中的效果了。

38. LinearLayout9:讓按鈕永遠釘在螢幕底部

這是「列表在上、操作按鈕在下」的經典版型。做法不是靠絕對定位,而是讓 ListView 主動把剩下的空間吃光。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <ListView android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1.0" />

    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_9_button" />

</LinearLayout>

第 16 行的 android:layout_weight="1.0" 就是全部的秘密。在垂直 LinearLayout 中,weight 代表「剩餘空間的分配比例」;ListView 拿走所有剩餘空間後被撐滿,Button 因為沒有 weight,就只佔 own wrap_content 的高度,自然被擠到最下方。這個技巧在聊天介面、表單頁、播放器控制列幾乎到處都用得到。

39. LinearLayout10:一行內的「標籤 + 輸入框 + 按鈕」

這是一個模仿輸入框外觀的自訂列,左邊文字、中間可編輯、右邊一顆星形圖示按鈕。

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:addStatesFromChildren="true"
    android:gravity="center_vertical"
    android:paddingRight="0dip"
    android:background="@android:drawable/edit_text">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/linear_layout_10_from"
        android:textColor="?android:attr/textColorSecondary"
        android:textAppearance="?android:attr/textAppearanceLargeInverse" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:singleLine="true"
        android:background="@null" />

    <ImageButton
        style="@android:style/Widget.Button.Inset"
        android:src="@android:drawable/star_big_on"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="2dip"
        android:layout_marginRight="2dip"
        android:layout_marginBottom="2dip"
        android:padding="10dip" />

</LinearLayout>

三個值得記住的細節:

  • android:addStatesFromChildren="true":讓容器把焦點/按下狀態「合併」子項的狀態,這樣整列才會跟著 EditText 一起顯示焦點效果。
  • EditText 上的 android:background="@null":拿掉內建底框,避免和外層 edit_text 背景疊出雙層線條。
  • EditText 的 layout_weight="1":讓輸入區自動吃掉中間所有剩餘寬度,無論文字標籤多長都不會把按鈕擠出去。

40. RelativeLayout1:相對布局的基準點概念

RelativeLayout 的強大之處在於「以其他元件為座標」。這個範例讓紅色塊貼上、綠色塊貼下,黃色塊則被拉伸填滿兩者之間的所有空間。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView android:id="@+id/view1"
        android:background="@drawable/red"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="@string/relative_layout_1_top" />

    <TextView android:id="@+id/view2"
        android:background="@drawable/green"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/relative_layout_1_bottom" />

    <TextView android:id="@+id/view3"
        android:background="@drawable/yellow"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_above="@id/view2"
        android:layout_below="@id/view1"
        android:text="@string/relative_layout_1_center" />

</RelativeLayout>

要盯住的四行:

  • 第 18 行 android:layout_alignParentTop="true"
  • 第 27 行 android:layout_alignParentBottom="true"
  • 第 36、37 行 android:layout_above="@id/view2" 與 android:layout_below="@id/view1"

view3 同時被「下方之上」與「上方之下」夾住,高度再設為 0dip,就會被動填滿中間區域。這種「用上下錨點撐開」的寫法,比去計算固定高度優雅得多,也是 RelativeLayout 最能發揮威力的場景。此外要留意引用順序:使用 @id/ 前置定義、或 @+id/ 直接宣告,兩者在舊版平台上行為略有差異,實務上建議被引用者先出現在檔案中。

41. ScrollView2:執行期動態塞進 64 個子視圖

ScrollView 只能有一個直接子節點,因此這裡在 XML 中先放一個 LinearLayout 當容器,再在 onCreate() 裡用迴圈把 TextView 與 Button 成對塞進去。

<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none">

    <LinearLayout android:id="@+id/layout"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/scroll_view_2_text_1" />

        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/scroll_view_2_button_1" />

    </LinearLayout>
</ScrollView>
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.scroll_view_2);

    LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
    for (int i = 2; i < 64; i++) {
        TextView textView = new TextView(this);
        textView.setText("Text View " + i);
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        layout.addView(textView, p);

        Button buttonView = new Button(this);
        buttonView.setText("Button " + i);
        layout.addView(buttonView, p);
    }
}

這裡有個實務上的提醒:LayoutParams 必須對應「父容器」的型別。因為父層是 LinearLayout,所以要 new LinearLayout.LayoutParams;若換成 RelativeLayout 或 TableRow 就得換成各自的 LayoutParams,否則會拿到錯誤的排列規則。另外,若真實專案要顯示幾百筆資料,應該改用 ListView/RecyclerView 做視圖回收,而不是像範例這樣全部塞進 ScrollView。

TableLayout 系列:從基本表格到動態控制

TableLayout 由 <TableRow> 組成,每一列裡的子元件自動依序填入第 0、1、2…欄。接下來 11 個範例其實就是在回答三個問題:欄寬怎麼分配、不要的格子怎麼留空、以及如何在執行期動態伸縮與隱藏欄位。

42. TableLayout1:最直覺的三列三欄

<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TableRow>
        <TextView android:text="@string/table_layout_1_star" android:padding="3dip" />
        <TextView android:text="@string/table_layout_1_open" android:padding="3dip" />
        <TextView android:text="@string/table_layout_1_open_shortcut" android:padding="3dip" />
    </TableRow>
    <TableRow>
        <TextView android:text="@string/table_layout_1_triple_star" android:padding="3dip" />
        <TextView android:text="@string/table_layout_1_save" android:padding="3dip" />
        <TextView android:text="@string/table_layout_1_save_shortcut" android:padding="3dip" />
    </TableRow>
    <TableRow>
        <TextView android:text="@string/table_layout_1_star" android:padding="3dip" />
        <TextView android:text="@string/table_layout_1_quit" android:padding="3dip" />
        <TextView android:text="@string/table_layout_1_quit_shortcut" android:padding="3dip" />
    </TableRow>
</TableLayout>

43. TableLayout2:空格子就不要放元件

要讓某格留白,最乾淨的做法就是「不寫」。若該元件偶爾才需要出現、平時只想保留佔位,則可搭配 android:visibility="invisible"(保留空間)或 gone(不保留空間)。

<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TableRow>
        <Button android:text="@string/table_layout_2_open" />
        <TextView android:text="@string/table_layout_2_path_1" android:padding="3dip" />
    </TableRow>
    <TableRow>
        <Button android:text="@string/table_layout_2_save_all" />
    </TableRow>
    <TableRow>
        <Button android:text="@string/table_layout_2_save"
            android:visibility="invisible" />
        <TextView android:text="@string/table_layout_2_path_2" android:padding="3dip" />
    </TableRow>
</TableLayout>

44. TableLayout4:左右兩端對齊的兩欄

關鍵是兩行屬性搭配使用:TableLayout 上宣告 android:stretchColumns="1" 讓第 1 欄吃掉剩餘寬度,再在第二欄元件上設 android:gravity="right" 把文字推到最右。

<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">

    <TableRow>
        <TextView android:text="@string/table_layout_4_open" android:padding="3dip" />
        <TextView android:text="@string/table_layout_4_open_shortcut"
            android:gravity="right" android:padding="3dip" />
    </TableRow>
    <TableRow>
        <TextView android:text="@string/table_layout_4_save" android:padding="3dip" />
        <TextView android:text="@string/table_layout_4_save_shortcut"
            android:gravity="right" android:padding="3dip" />
    </TableRow>
</TableLayout>

這裡要特別區分一組容易混淆的屬性:android:gravity 管的是「元件內容在自己範圍內怎麼靠」,android:layout_gravity 管的才是「元件本身在儲存格裡怎麼靠」。兩者效果完全不同,混用是初學者最常踩的坑。

45. TableLayout5:用 View 畫分隔線

想要在選單中插入分隔線,不需要任何自訂元件,只要放一個高度 2dip、指定背景色的空 View 即可:

<View
    android:layout_height="2dip"
    android:background="#FF909090" />

在 TableLayout 中,這個 View 會自成一列並橫向貫穿整個表格寬度,效果等同


。範例裡它被插在「儲存」與「匯入」區塊之間,以及「匯出」與「結束」之間,形成清楚的視覺分組。

46. TableLayout6:用 layout_column 跳欄

第 12 行的 android:layout_column="1" 明確宣告該 TextView 屬於第 1 欄。這個屬性的價值在於「跳位」:當某一列需要對齊其他列的欄位,卻又不想在前面補空白元件時,直接指定欄索引即可,程式碼乾淨很多。

<TableRow>
    <TextView
        android:layout_column="1"
        android:text="@string/table_layout_6_open"
        android:padding="3dip" />
    <TextView
        android:text="@string/table_layout_6_open_shortcut"
        android:gravity="right"
        android:padding="3dip" />
</TableRow>

47. TableLayout7:動態隱藏整欄

第 12 行的 android:collapseColumns="2" 表示第 2 欄(快捷鍵那一欄)初始為折疊狀態。注意這裡隱藏的是「欄」而不是「列」——原範例標題寫成列,實際行為是整欄消失。

<TableLayout
    android:id="@+id/menu"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="1"
    android:collapseColumns="2">
    ...
</TableLayout>

兩個切換按鈕的事件:

final TableLayout table = (TableLayout) findViewById(R.id.menu);

Button button = (Button) findViewById(R.id.toggle1);
button.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
        mShortcutsCollapsed = !mShortcutsCollapsed;
        table.setColumnCollapsed(2, mShortcutsCollapsed);
    }
});

button = (Button) findViewById(R.id.toggle2);
button.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
        mCheckmarksCollapsed = !mCheckmarksCollapsed;
        table.setColumnCollapsed(0, mCheckmarksCollapsed);
    }
});

48. TableLayout8:動態切換 stretch

final TableLayout table = (TableLayout) findViewById(R.id.menu);
Button button = (Button) findViewById(R.id.toggle);
button.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
        mStretch = !mStretch;
        table.setColumnStretchable(1, mStretch);
    }
});

49. TableLayout9:動態切換 shrink

final TableLayout table = (TableLayout) findViewById(R.id.menu);
Button button = (Button) findViewById(R.id.toggle);
button.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v) {
        mShrink = !mShrink;
        table.setColumnShrinkable(0, mShrink);
    }
});

官方對 setColumnShrinkable() 的說明大意是:讓指定欄位變得「可壓縮」。當某一列內容太寬、超出可用空間時,表格就能從可壓縮的欄位回收多餘空間。呼叫此方法會觸發一次新的布局計算(layout pass),這也是為什麼它能立即生效。

把 stretch 與 shrink 放在一起理解最清楚:stretch 是「有多的空間給我」,shrink 是「空間不夠從我這裡扣」。兩者可以在同一個表格上並存。

50. TableLayout10:登入表單

同樣靠 android:stretchColumns="1" 讓輸入框吃掉剩餘寬度;標籤欄用 android:gravity="right" 靠右對齊,讓兩行的冒號位置整齊。密碼欄的 android:password="true" 負責把輸入內容轉為圓點,android:scrollHorizontally="true" 則讓過長的內容單向捲動而不換行。

<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">

    <TableRow>
        <TextView android:text="@string/table_layout_10_user"
            android:textStyle="bold" android:gravity="right" android:padding="3dip" />
        <EditText android:id="@+id/username"
            android:text="@string/table_layout_10_username_text"
            android:padding="3dip" android:scrollHorizontally="true" />
    </TableRow>

    <TableRow>
        <TextView android:text="@string/table_layout_10_password"
            android:textStyle="bold" android:gravity="right" android:padding="3dip" />
        <EditText android:id="@+id/password"
            android:text="@string/table_layout_10_password_text"
            android:password="true" android:padding="3dip"
            android:scrollHorizontally="true" />
    </TableRow>

    <TableRow android:gravity="right">
        <Button android:id="@+id/cancel" android:text="@string/table_layout_10_cancel" />
        <Button android:id="@+id/login" android:text="@string/table_layout_10_login" />
    </TableRow>
</TableLayout>

最後一列把 android:gravity="right" 放在 TableRow 上,效果是整列的所有儲存格內容一起靠右,比在每顆按鈕上個別設定省事。

51. TableLayout11:layout_gravity 與背景色的實驗

這個範例刻意用綠、紅、洋紅、青等強烈背景色,把每一格實際佔用的範圍視覺化,用來觀察 layout_gravity 造成的差異:

<TableRow>
    <!-- 儲存格內容水平置中 -->
    <TextView
        android:layout_column="1"
        android:text="@string/table_layout_7_save_as"
        android:background="#FFFF0000"
        android:layout_gravity="center_horizontal"
        android:padding="3dip" />
    <TextView
        android:text="@string/table_layout_7_save_as_shortcut"
        android:background="#FFFF00FF"
        android:gravity="right"
        android:padding="3dip" />
</TableRow>

<TableRow>
    <View android:layout_height="68dip" android:background="#FF909090" />
    <!-- 儲存格內容靠右下 -->
    <TextView
        android:text="@string/table_layout_7_export"
        android:background="#FFFF0000"
        android:layout_gravity="right|bottom"
        android:padding="3dip" />
    <TextView
        android:text="@string/table_layout_7_export_shortcut"
        android:background="#FF00FFFF"
        android:gravity="right"
        android:padding="3dip" />
</TableRow>

刻意把第一欄的 View 高度設成 68dip,就能清楚看到:設了 layout_gravity="right|bottom" 的 TextView 會被推到儲存格的右下角,而沒設的元件則預設貼左上。layout_gravity 支援 | 組合多個方向,這是對齊單一儲存格內容時的首選工具。

52. TableLayout12:用 layout_span 合併儲存格

第 26 行的 android:layout_span="2" 讓這個 TextView 橫跨兩格;第 67 行更進一步用 layout_span="3" 讓一整列合併成單一儲存格,適合放標題或說明文字。

<TableRow>
    <TextView android:text="@string/table_layout_12_d"
        android:layout_span="2"
        android:gravity="center_horizontal"
        android:background="#FF0000FF"
        android:padding="3dip" />
    <TextView android:text="@string/table_layout_12_e"
        android:background="#FF00FF00"
        android:padding="3dip" />
</TableRow>

<TableRow>
    <TextView android:text="@string/table_layout_12_g"
        android:layout_span="3"
        android:gravity="center_horizontal"
        android:background="#FFC0C0C0"
        android:padding="3dip" />
</TableRow>

要留意的是:使用 span 之後,該列的欄位索引會重新計算。若後續还想用 layout_column 對齊,必須把 span 造成的位移一起算進去,否則很容易錯位。

清單範例:從自訂行到可展開內容

53. List4:在 List 裡再嵌一層 LinearLayout

ListActivity 只要換上自訂 Adapter,就能讓每一列長成完全不同的樣子。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Use our own list adapter
    setListAdapter(new SpeechListAdapter(this));
}

54. List5:讓分隔線變成不可點擊

上圖中「為沒能點的空白」就是分隔列。做法非常聰明:資料陣列裡用一串 "----------" 充當分隔項,再由 Adapter 判斷開頭字元決定要不要啟用。

@Override
public boolean areAllItemsEnabled() {
    return false;
}

@Override
public boolean isEnabled(int position) {
    return !mStrings[position].startsWith("-");
}

areAllItemsEnabled() 回傳 false 是前提,它告訴 ListView「並非每一項都可點」,這之後 isEnabled() 的逐項判斷才會被採用。getView 的部分則是標準的 convertView 複用寫法:

public View getView(int position, View convertView, ViewGroup parent) {
    TextView tv;
    if (convertView == null) {
        tv = (TextView) LayoutInflater.from(mContext).inflate(
                android.R.layout.simple_expandable_list_item_1, parent, false);
    } else {
        tv = (TextView) convertView;
    }
    tv.setText(mStrings[position]);
    return tv;
}

55. List6:點擊展開/收合內容的 ListActivity

這是本篇設計上最有意思的範例:每一列只有標題,點一下才把對應的內容展開。整個實作可以拆成四個步驟。

步驟一:在 onCreate() 掛上自訂 Adapter。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new SpeechListAdapter(this));
}

步驟二:Adapter 內部用 mTitles 與 mDialogue 兩個陣列存資料,再用 boolean 陣列 mExpanded 記錄每一列的展開狀態。

public View getView(int position, View convertView, ViewGroup parent) {
    SpeechView sv;
    if (convertView == null) {
        sv = new SpeechView(mContext, mTitles[position],
                mDialogue[position], mExpanded[position]);
    } else {
        sv = (SpeechView) convertView;
        sv.setTitle(mTitles[position]);
        sv.setDialogue(mDialogue[position]);
        sv.setExpanded(mExpanded[position]);
    }
    return sv;
}

public void toggle(int position) {
    mExpanded[position] = !mExpanded[position];
    notifyDataSetChanged();
}

步驟三:自訂 SpeechView,本質上就是一個垂直 LinearLayout 內含兩個 TextView,用 setVisibility() 控制第二行是否顯示。

private class SpeechView extends LinearLayout {
    public SpeechView(Context context, String title, String dialogue,
            boolean expanded) {
        super(context);
        this.setOrientation(VERTICAL);

        mTitle = new TextView(context);
        mTitle.setText(title);
        addView(mTitle, new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        mDialogue = new TextView(context);
        mDialogue.setText(dialogue);
        addView(mDialogue, new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

        mDialogue.setVisibility(expanded ? VISIBLE : GONE);
    }

    public void setTitle(String title) { mTitle.setText(title); }
    public void setDialogue(String words) { mDialogue.setText(words); }
    public void setExpanded(boolean expanded) {
        mDialogue.setVisibility(expanded ? VISIBLE : GONE);
    }

    private TextView mTitle;
    private TextView mDialogue;
}

步驟四:覆寫 onListItemClick,把點擊位置轉交給 Adapter 的 toggle。

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    ((SpeechListAdapter) getListAdapter()).toggle(position);
}

整個流程的閉環在 notifyDataSetChanged():它通知 ListView 底層資料已變動,需要重新繪製。少了這一句,畫面不會有任何反應。

56. List8:有內容顯示列表、無內容顯示提示

布局結構是「上方一橫排按鈕 + 下方 FrameLayout」。FrameLayout 裡同時放 ListView 與 TextView,兩者重疊,由 ListActivity 依資料量自動切換顯示哪一個。

最關鍵的是第 34 行:<ListView android:id="@android:id/list" />。在 ListActivity 中,ListView 的 id 必須是系統預設的 @android:id/list,否則 getListView() 會找不到對象而拋出例外。

<FrameLayout
    android:layout_width="fill_parent"
    android:layout_height="0dip"
    android:layout_weight="1" >

    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"/>

    <TextView android:id="@+id/empty"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/list_8_no_photos"/>

</FrameLayout>

程式端先指定空清單時要顯示的替代視圖,再掛上自訂的 PhotoAdapter:

setContentView(R.layout.list_8);
getListView().setEmptyView(findViewById(R.id.empty));
mAdapter = new PhotoAdapter(this);
setListAdapter(mAdapter);

PhotoAdapter 的 getView 直接回傳一個 ImageView,並用 setAdjustViewBounds(true) 保持圖片原始比例:

public View getView(int position, View convertView, ViewGroup parent) {
    ImageView i = new ImageView(mContext);
    i.setImageResource(mPhotos.get(position));
    i.setAdjustViewBounds(true);   // 保持圖片比例
    i.setLayoutParams(new AbsListView.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    i.setBackgroundResource(R.drawable.picture_frame);
    return i;
}

兩個按鈕分別呼叫 Adapter 的清空與新增方法,資料源是一個存放資源 id 的 ArrayList:

public void clearPhotos() {
    mPhotos.clear();
    notifyDataSetChanged();
}

public void addPhotos() {
    int whichPhoto = (int) Math.round(Math.random() * (mPhotoPool.length - 1));
    int newPhoto = mPhotoPool[whichPhoto];
    mPhotos.add(newPhoto);
    notifyDataSetChanged();
}

57. List10:單選清單

要讓清單變成單選,只需要換成內建的 single choice 行布局,再設定 choiceMode。整個 Activity 的 onCreate 就只有這樣:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setListAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_single_choice, GENRES));

    final ListView listView = getListView();
    listView.setItemsCanFocus(false);
    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);  // 單選
}

setItemsCanFocus(false) 的作用是讓焦點停留在「選取」層級而非行內的子元件,這對含核取方塊或單選鈕的行是必要的設定,否則方向鍵操作會出現焦點被行內控制項搶走的怪異行為。

小結

這一段範例如果要用一句話總結,那就是:布局屬性寫在 XML 只是起點,真正的彈性來自執行期的 API。LinearLayout 的 weight 與 gravity、RelativeLayout 的錨點、TableLayout 的 stretch/shrink/collapse/span,每一項都有對應的 setter,可以在使用者操作時即時改變。理解「哪個屬性對應哪個方法」,比背誦單一寫法重要得多。

另外值得養成習慣的是:TableLayout 的 gravity 與 layout_gravity、ListView 的 areAllItemsEnabled 與 isEnabled、以及 convertView 的複用機制——這三組觀念釐清之後,多數「怎麼設都跑不出來」的問題都會迎刃而解。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved