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

Android 開發雜記(一):空列表提示、可見性屬性與 Fragment 通訊

編輯:關於 Android 程式設計

一些零散但反覆會用到的筆記,平時查到就記下來。

一、ListView 內容為空時的處理

使用 ListView 或 GridView 時,當資料來源為空,往往需要在列表位置顯示一個特殊的 empty view 來提示使用者(「暫無資料」「載入失敗,請重試」之類)。

Android 內建了這個能力,用 setEmptyView() 一行就能接上:

private void setupViews() {
    mListView = (ListView) findViewById(R.id.list);
    ((ViewGroup) mListView.getParent()).addView(mErrorView);
    mListView.setEmptyView(mErrorView);
    mProgressBar = (ProgressBar) findViewById(R.id.pb_progress);
}

它的運作原理是:ListView(實際上是 AdapterView)內部會監聽 Adapter 的資料變化,當 getCount() 回傳 0 時自動顯示 empty view,並隱藏自己;一旦有資料又反過來。整個切換不需要你寫任何判斷。

幾個實務細節:

empty view 必須已經在布局中,或者像上面這樣先 addView 進去。設為 invisible 也可以,但設為 gone 的話 ListView 找不到它的 LayoutParams,可能出問題。

empty view 與 ListView 應該是兄弟關係而非父子。AdapterView 只接受特定類型的子 View,把 TextView 塞進 ListView 裡會拋例外。常見做法是在布局中用 FrameLayout 把兩者疊放:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:id="@+id/empty_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="暫無資料" />
</FrameLayout>

它判斷的是 count 而非 loading 狀態。所以網路請求進行中時,empty view 也會顯示(因為此時 count 為 0)。實務上通常把 empty view 的文案設計成「載入中…」,或者另外用一個旗標控制它的可見性,請求完成後再依結果切換文案。

RecyclerView 沒有這個方法。從 ListView 遷移到 RecyclerView 後,setEmptyView 不復存在,需要自己實作——通常是觀察 Adapter 的資料變化並手動切換可見性,或者用 ConcatAdapter 把 empty view 當成一個獨立的 ViewType 拼進去。

二、android:visibility 的三種屬性

Android 中控件或布局的可見性有三種狀態:View.VISIBLE、View.INVISIBLE、View.GONE。

View.VISIBLE——正常顯示,佔據布局空間。

View.INVISIBLE——不可見,但仍然佔據空間。也就是說控件隱藏了,畫面上它原本的位置還是留著一個空洞。這一點與 C# 的 Visible 屬性含義不同,是從其他平台轉過來最容易誤解的地方。

View.GONE——不可見,且不佔據系統布局中的任何空間。後續的控件會往前補位。

選擇依據很直接:要保留版面配置就 invisible,要讓後面的元素補位就 gone。前面〈來電管家(二)〉中 CheckBox 的 invisible 設定就是為了保持文字寬度不變,而刪除模式切換時底部操作列用 gone 則是為了讓列表重新佔滿整個高度。

補充一個效能面向:GONE 的 View 完全不參與 measure 與 layout 流程,而 INVISIBLE 的 View 仍然會被測量與配置(只是不繪製)。在深层布局中大量使用 INVISIBLE 會帶來不必要的測量開銷。

三、Fragment 的事件回呼與資料溝通

某些情況下需要 Fragment 與 Activity 共享事件。一個得體的做法是在 Fragment 中定義回呼介面,要求宿主 Activity 實作它。

舉個典型例子:一個新聞閱讀應用,某個 Activity 中並置兩個 Fragment——FragmentA 顯示文章標題列表,FragmentB 顯示文章內容。當使用者點選某篇文章時,FragmentA 必須通知 Activity,Activity 再通知 FragmentB 去載入對應內容。

為什麼不直接讓 FragmentA 呼叫 FragmentB?因為Fragment 之間不應該直接互相引用。它們可能處於不同的容器、不同的生命週期階段,直接耦合會導致難以除錯的狀態問題。以 Activity 作為中介,是官方文件明確建議的做法。

步驟一:在 FragmentA 中宣告介面

public static class FragmentA extends ListFragment {

    // 容器 Activity 必須實作這個介面
    public interface OnArticleSelectedListener {
        public void onArticleSelected(Uri articleUri);
    }

    // ...
}

注意參數設計:傳的是 Uri 而非整篇文章物件。這是有意的鬆耦合——FragmentA 只負責告訴 Activity「使用者選了這個 id」,至於怎麼取內容、從哪裡取,完全不是它的事。

步驟二:在 onAttach() 中取得並驗證

public static class FragmentA extends ListFragment {
    OnArticleSelectedListener mListener;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnArticleSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnArticleSelectedListener");
        }
    }
    // ...
}

onAttach() 是 Fragment 被加入 Activity 時由系統呼叫的,在這裡做型別轉換最合適——契約驗證應該發生在最早的可能時機,讓錯誤立刻暴露而不是延後到使用者點擊時才崩潰。

catch 之後重新 throw 並附上有意義的訊息,這個寫法值得學:系統原本拋的 ClassCastException 訊息通常很難讀,補充「哪個 Activity 沒實作哪個介面」能省下大量除錯時間。

步驟三:在事件發生時通知

public static class FragmentA extends ListFragment {
    OnArticleSelectedListener mListener;

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // 把點擊項目的 row ID 附加到 content provider 的 Uri 上
        Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id);
        // 把事件與 Uri 送給宿主 Activity
        mListener.onArticleSelected(noteUri);
    }
}

ContentUris.withAppendedId() 是 Android 的慣用手法:把 id 拼到 ContentProvider 的基底 Uri 後面,形成指向單筆資料的 Uri。這樣 Activity 拿到的不只是一個數字,而是一個可以直接交給 ContentResolver.query() 使用的完整參照。

步驟四:Activity 實作介面並轉發

public class MainActivity extends Activity
        implements FragmentA.OnArticleSelectedListener {

    @Override
    public void onArticleSelected(Uri articleUri) {
        FragmentB fragB = (FragmentB)
                getFragmentManager().findFragmentById(R.id.article_fragment);
        fragB.displayArticle(articleUri);
    }
}

Activity 在這裡扮演單純的轉發者:收到通知,找到 FragmentB,把 Uri 交過去。它自己也可能是 Fragment 的宿主,因此這個模式可以層層串接。

幾個實務補充

記得在 onDetach() 中清理參照。若 mListener 是強參照,Activity 銷毀而 Fragment 因某種原因仍存活時會造成洩漏。嚴謹的寫法是在 onDetach() 中設為 null,或者改用弱參照。

Kotlin 的介面參數可以給預設實作。用 interface 搭配 default method,讓 Activity 不必實作所有回呼:

interface OnArticleSelectedListener {
    fun onArticleSelected(articleUri: Uri) {}
}

更現代的替代方案。上面的寫法來自 Fragment 較早期的年代。現在的推薦做法:

· Fragment Result API(fragment-ktx 1.3.0 以上)——用 setFragmentResultListener 在 FragmentManager 層級傳遞資料,完全不需要自訂介面。

// FragmentA 發送
setFragmentResult("requestKey", bundleOf("articleUri" to uri.toString()))

// Activity 或 FragmentB 接收
supportFragmentManager.setFragmentResultListener("requestKey", this) { _, bundle ->
    val uri = Uri.parse(bundle.getString("articleUri"))
}

· 共用 ViewModel——用 activityViewModels() 讓兩個 Fragment 共享同一個 ViewModel 實例,資料變更自動同步,連事件都不用發。這在需要雙向溝通時特別合適。

· Navigation 組件的 Safe Args——處理帶參數的頁面跳轉。

不過「Fragment 不直接互相引用、透過宿主或共用元件溝通」這個原則從來沒變。變的只是實作它的工具變得更安全、更省程式碼。

四、Action Bar

關於 Action Bar 的詳細用法可參考相關專文,這裡只列一個重點演進脈絡:ActionBar(API 11 引入)→ 由 Toolbar 取代(API 21 / AppCompat)→ 現在多數專案直接使用 Material Design 的 TopAppBar 或 Jetpack Compose 的 TopAppBar。核心 API 從 Activity 的 getActionBar() 轉變為 setSupportActionBar(toolbar),但選單的建立(onCreateOptionsMenu)與分派(onOptionsItemSelected)機制始終一致。

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