Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

來電管家實作(一):ActivityGroup 分頁界面設計

編輯:關於 Android 程式設計

這幾天忙著寫來電管家這個小工具,主體功能基本完成,剩下後續打磨。(之前的記事本專案擱著沒動,但不會放棄。)

來電管家的核心就是攔截,具體拆成四項:

1. 黑名單 / 白名單管理

2. 攔截模式選擇

3. 啟用攔截時間段

4. 攔截總開關

整體流程是:使用者開啟攔截並選擇模式,App 啟動後台監聽服務攔截來電並判斷是否掛斷;同時可設定啟用的時間段,只有落在該區間內才真正生效。

界面預覽

從畫面看得出來,這裡用的是 ActivityGroup + Activity 的組合來達到分頁標籤的效果,跟 QQ 那類應用的做法一致。核心概念是:ActivityGroup 作為容器,把每個子 Activity 轉換成 View 塞進自己的布局裡,切換分頁時替換 View 而非啟動新 Activity。

一、主布局

<?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">

    <RelativeLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent">

        <GridView
            android:id="@+id/gvTopBar"
            android:layout_height="35dp"
            android:layout_width="fill_parent"
            android:layout_alignParentTop="true"
            android:background="@drawable/tabbar_bg"
            android:layout_centerVertical="true">
        </GridView>

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/gvTopBar"
            android:src="@drawable/line" />

        <LinearLayout
            android:id="@+id/Container"
            android:layout_below="@+id/gvTopBar"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical">
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

三個元件各司其職:GridView 放頂部的分頁菜單,ImageView 是分隔用的虛線,最下面的 LinearLayout(Container)是承載四個子頁面的容器。

二、四個子頁面的布局

黑名單頁(activity_add.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"
    android:orientation="vertical"
    android:id="@+id/layout">

    <ListView
        android:id="@+id/lv_show"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:cacheColorHint="#FFF">
    </ListView>

    <RelativeLayout
        android:id="@+id/add_layout"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:visibility="visible"
        android:background="@drawable/tabbar_bg">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/line" />
        <Button
            android:id="@+id/btn_add"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_centerHorizontal="true"
            android:background="@drawable/add" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/delete_layout"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:visibility="gone"
        android:background="@drawable/tabbar_bg">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/line" />
        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:background="@drawable/backup" />
        <TextView
            android:id="@+id/tv_select"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="共選擇了 項"
            android:layout_centerInParent="true" />
        <Button
            android:id="@+id/btn_delete"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_alignParentRight="true"
            android:background="@drawable/delete" />
    </RelativeLayout>
</LinearLayout>

這裡有個值得學的設計:add_layout 與 delete_layout 重疊放在同一位置,靠 visibility 互斥切換。一般模式顯示「新增」按鈕,刪除模式切換成「取消 / 已選數量 / 刪除」三件套。用同一個容器不重排布局,切換時不會跳動。

另外 ListView 上的 cacheColorHint="#FFF" 是在自訂背景色時避免捲動出現-black 色塊的常用技巧。

攔截記錄頁(activity_callInfo.xml):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/lv_show_callInfo"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1">
    </ListView>

    <RelativeLayout
        android:id="@+id/add_layout"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:layout_alignParentBottom="true"
        android:background="@drawable/tabbar_bg">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/line" />
        <Button
            android:id="@+id/btn_delete_callInfo"
            android:layout_width="45dp"
            android:layout_height="45dp"
            android:layout_centerHorizontal="true"
            android:background="@drawable/delete" />
    </RelativeLayout>
</RelativeLayout>

設定頁(activity_setting.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"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:gravity="center"
        android:padding="8dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp"
        android:background="@drawable/setting_top">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="開啟監聽"
            android:textSize="15sp" />
        <ToggleButton
            android:id="@+id/tb_switch"
            android:layout_width="44dp"
            android:layout_height="20dp"
            android:background="@drawable/start_service_off"
            android:textOff=""
            android:textOn=""
            android:layout_alignParentRight="true" />
    </RelativeLayout>

    <!-- 白名單模式:setting_middle 背景 -->
    <RelativeLayout ... >
        <TextView android:text="白名單模式" ... />
        <ToggleButton android:id="@+id/tb_whitelist" ... />
    </RelativeLayout>

    <!-- 啟用時間段:setting_middle 背景 -->
    <RelativeLayout ... >
        <TextView android:text="啟用時間段" ... />
        <ToggleButton android:id="@+id/tb_time" ... />
    </RelativeLayout>

    <!-- 開始時間 -->
    <RelativeLayout android:id="@+id/start_layout" ... >
        <TextView android:id="@+id/tv_start_tip" android:text="開始時間" ... />
        <TextView android:id="@+id/tv_start_time"
                  android:layout_alignParentRight="true" ... />
    </RelativeLayout>

    <!-- 結束時間:setting_under 背景 -->
    <RelativeLayout android:id="@+id/end_layout" ... >
        <TextView android:id="@+id/tv_end_tip" android:text="結束時間" ... />
        <TextView android:id="@+id/tv_end_time"
                  android:layout_alignParentRight="true" ... />
    </RelativeLayout>
</LinearLayout>

設定頁的視覺重點是那圈圓角邊框,靠的是 .9.png(NinePatch)圖片。這裡用了一個常見技巧:把整組設定項串成一條,只有最上面那筆用 setting_top 背景、最下面用 setting_under,中間幾筆用 setting_middle,就能拼出「一個圓角卡片包著多行」的效果,而不必真的做一個大容器。

ToggleButton 上的 android:textOn="" 與 android:textOff="" 是必要的——預設會在按鈕上顯示「ON / OFF」字樣,設成空字串後才能純靠背景圖表達狀態。

三、頂部分頁菜單的實作

既然用 GridView,就必須有 Adapter。這裡自訂了一個 BaseAdapter:

package com.example.callmanager;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

public class TabBarAdapter extends BaseAdapter {

    private Context mContext;
    private TextView[] txtItems;
    private int selResId;

    public TabBarAdapter(Context c, int[] tabMenuId, int width, int height, int selResId) {
        mContext = c;
        this.selResId = selResId;
        txtItems = new TextView[tabMenuId.length];
        for (int i = 0; i < tabMenuId.length; i++) {
            txtItems[i] = new TextView(mContext);
            txtItems[i].setLayoutParams(
                new GridView.LayoutParams(width, GridView.LayoutParams.WRAP_CONTENT));
            txtItems[i].setGravity(Gravity.CENTER);
            txtItems[i].setPadding(2, 5, 2, 5);
            txtItems[i].setText(tabMenuId[i]);
            txtItems[i].setTextSize(15);
        }
    }

    public int getCount() { return txtItems.length; }
    public Object getItem(int position) { return position; }
    public long getItemId(int position) { return position; }

    /** 設定選中的效果 */
    public void SetFocus(int index) {
        for (int i = 0; i < txtItems.length; i++) {
            if (i != index) {
                txtItems[i].setBackgroundResource(0);   // 恢復未選中樣式
            }
        }
        txtItems[index].setBackgroundResource(selResId);  // 設定選中樣式
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        TextView textView;
        if (convertView == null) {
            textView = txtItems[position];
        } else {
            textView = (TextView) convertView;
        }
        return textView;
    }
}

這個 Adapter 的做法相當取巧:在構造函數中就把所有 TextView 建好並存進陣列,getView 直接回傳對應的物件。因為分頁數量固定且極少(這裡只有四個),這樣做完全可行,而且省下了每次捲動重建的開銷。SetFocus() 則負責切換高亮——先把其他全部重設為無背景,再把指定的設成選中背景,選中樣式同樣用的是 .9.png。

綁定到 GridView:

public GridView gvTopBar;
private TabBarAdapter topImgAdapter;

/** 頂部菜單 */
int[] topbar_menu_array = {
    R.string.black_list, R.string.white_list,
    R.string.call_info, R.string.setting
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    gvTopBar = (GridView) this.findViewById(R.id.gvTopBar);
    gvTopBar.setNumColumns(topbar_menu_array.length);      // 設定每行列數
    gvTopBar.setSelector(new ColorDrawable(Color.TRANSPARENT));  // 點擊效果設為透明
    gvTopBar.setGravity(Gravity.CENTER);                   // 位置居中

    int width = this.getWindowManager().getDefaultDisplay().getWidth()
                / topbar_menu_array.length;                  // 平均分配寬度
    topImgAdapter = new TabBarAdapter(this, topbar_menu_array, width, 48,
                                      R.drawable.menu_background);
    gvTopBar.setAdapter(topImgAdapter);
}

這裡有兩個實務技巧:setSelector(new ColorDrawable(Color.TRANSPARENT)) 拿掉 GridView 預設的點擊高亮方塊,讓視覺完全由 item 自身的背景控制;用螢幕寬度除以項目數計算每格寬度,能讓四個分頁剛好平均填滿螢幕,不必為不同解析度各寫一份 dimens。

四、把子 Activity 掛進容器

ActivityGroup 的用法核心在 getLocalActivityManager():

public LinearLayout container;   // 裝載 sub Activity 的容器

gvTopBar.setOnItemClickListener(new ItemClickEvent());   // 項目點擊事件
container = (LinearLayout) findViewById(R.id.Container);
SwitchActivity(0);   // 預設打開第 0 頁

class ItemClickEvent implements OnItemClickListener {
    @SuppressLint("NewApi")
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        SwitchActivity(arg2);
    }
}

/**
 * 依 ID 打開指定的 Activity
 * @param id GridView 選中項的序號
 */
void SwitchActivity(int id) {
    topImgAdapter.SetFocus(id);          // 選中項獲得高亮
    container.removeAllViews();          // 必須先清除容器中所有的 View

    Intent intent = null;
    if (id == 0)      intent = new Intent(ActivityGroupDemo.this, BlackListActivity.class);
    else if (id == 1) intent = new Intent(ActivityGroupDemo.this, WhiteListActivity.class);
    else if (id == 2) intent = new Intent(ActivityGroupDemo.this, CallInfo.class);
    else if (id == 3) intent = new Intent(ActivityGroupDemo.this, SettingActivity.class);

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Activity 轉為 View
    Window subActivity = getLocalActivityManager()
                            .startActivity("subActivity", intent);

    // 容器添加 View
    container.addView(subActivity.getDecorView(),
                      LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}

流程就是三個動作:用 Intent 指定要顯示哪個子 Activity → 交給 LocalActivityManager 啟動並取得它的 DecorView → 把這個 View 加進容器。

兩個關鍵點:removeAllViews() 必須先呼叫,否則新頁會疊在舊頁上面;startActivity 的第二個參數是 id,這裡固定用 "subActivity",讓同一個 id 對應到不同的內容,LocalActivityManager 會負責管理狀態保存。

關於 ActivityGroup 的現實提醒

ActivityGroup 從 Android 1.5 就存在,但在 API 13 起已被標記為 Deprecated。它內建在同一個 Activity 內管理多個子 Activity 生命週期,而這種嵌套在後續版本中容易引發狀態保存、記憶體洩漏與生命週期回呼順序的問題。

現行的標準做法是 Fragment + FragmentPagerAdapter / ViewPager2,或使用 BottomNavigationView / TabLayout 搭配 Navigation 組件。Fragment 天生就是「可嵌入的 UI 單元」,每個分頁有自己的生命週期且受宿主 Activity 管理,不必再靠 LocalActivityManager 這種重量級機制。

不過這篇的價值在於把「分頁界面」的構成要素講清楚了:頂部菜單(Adapter + GridView 或 TabLayout)、內容容器、切換邏輯。這三塊換成任何技術實作都成立,理解結構比記住 API 重要。

至此界面設計部分完成,後續再來談具體的攔截功能實作。

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