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

Android 動態載入版面配置:不用 TabHost 也能換頁

編輯:關於 Android 程式設計

前陣子專案有個需求:同一個頁面要依不同按鈕載入不同的版面。原本想用 TabHost,但美工給的設計稿完全用不上頁籤樣式,所以改走「動態載入」這條路。整理成 DEMO 記錄如下。

先畫出框架

中間白色區域是一個空的 LinearLayout,用來承載動態載入的版面。我畫圖時習慣用不同顏色標示不同區塊,方便對照。

主版面 main.xml

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

    <LinearLayout android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button android:text="加載ListView"
            android:id="@+id/Button01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </Button>
        <Button android:text="加載另外一個頁面"
            android:id="@+id/Button02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"></Button>
    </LinearLayout>

    <!-- 這塊白色區域用來動態載入傳進來的版面 -->
    <LinearLayout android:id="@+id/LinearLayout01"
        android:background="#FFFFFF"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"></LinearLayout>

</LinearLayout>

準備要被載入的版面

先準備一個用來放 ListView 的版面 listview.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <ListView android:id="@+id/ListView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></ListView>
</LinearLayout>

ListView 每一列的樣式 list_view_row.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <TextView android:text="@+id/TextView01"
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></TextView>
</LinearLayout>

另一個用來驗證「確實換了版面」的簡單頁面 hello.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout android:id="@+id/hellolayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <TextView android:text="HELLO"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></TextView>
</LinearLayout>

ListView 的 Adapter

package com.terry;

import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class listAdapter extends BaseAdapter {
    ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
    private LayoutInflater inflater;

    public listAdapter(Context contex) {
        inflater = LayoutInflater.from(contex);
        for (int i = 0; i < 10; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("name", "例子" + i);
            list.add(map);
        }
    }

    @Override public int getCount() { return list.size(); }

    @Override public Object getItem(int position) { return list.get(position); }

    @Override public long getItemId(int position) { return position; }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final viewHolder myHolder;
        if (convertView == null) {
            myHolder = new viewHolder();
            convertView = inflater.inflate(R.layout.list_view_row, null);
            myHolder.tv = (TextView) convertView.findViewById(R.id.TextView01);
            convertView.setTag(myHolder);
        } else {
            myHolder = (viewHolder) convertView.getTag();
        }
        myHolder.tv.setText(list.get(position).get("name").toString());
        return convertView;
    }

    static class viewHolder {
        TextView tv;
    }
}

這裡用了 ViewHolder 模式(setTag/getTag)避免重複 findViewById,是列表效能的基本功。

專案結構如下:

動態載入的核心程式碼

點擊第一個按鈕:

點擊第二個按鈕:

package com.terry;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

public class dynaActivity extends Activity {

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

        final LayoutInflater inflater = LayoutInflater.from(this);
        Button btn = (Button) findViewById(R.id.Button01);
        Button btn2 = (Button) findViewById(R.id.Button02);
        final LinearLayout lin = (LinearLayout) findViewById(R.id.LinearLayout01);

        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout layout = (LinearLayout) inflater.inflate(
                        R.layout.listview, null).findViewById(R.id.layout);
                ListView lv = (ListView) layout.getChildAt(0);
                lv.setAdapter(new listAdapter(dynaActivity.this));
                lin.removeAllViews();     // 先清掉舊的
                lin.addView(layout);      // 再放新的
            }
        });

        btn2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                LinearLayout layout = (LinearLayout) inflater.inflate(
                        R.layout.hello, null).findViewById(R.id.hellolayout);
                TextView tv = (TextView) layout.getChildAt(0);
                tv.setTextColor(Color.RED);
                lin.removeAllViews();
                lin.addView(layout);
            }
        });
    }
}

原理就是:用 LayoutInflater 把目標版面讀成 View 物件,找到裡面的子 View 做操作,最後掛進 setContentView 裡預留的容器中。每次動態載入前一定要呼叫 removeAllViews(),否則舊 View 會疊在新 View 底下,造成「換頁後內容重疊」的經典 bug。

幾個實務提醒

  • 每次點擊都重新 inflate 有成本。若切換頻繁,可以先把各版面 inflate 好放在記憶體或 SparseArray 裡,切換時只做 removeAllViews + addView,省下解析 XML 的時間。
  • 動態載入的 View 記得回收監聽器。若版面裡有註冊了 OnTouchListener、動畫或 Timer,換頁時要一併停止,否則容易記憶體洩漏。
  • 換頁加點動畫會好很多。因為操作的是 View 層級,可以直接套 Animation 或 Transition 做淡入淡出、平移,觀賞性提升明顯。
  • 什麼時候該用 Fragment 而不是動態載入?如果每個「頁」都有自己的生命週期、需要獨立管理資料與返回鍵行為,Fragment(搭配 FragmentTransaction.replace())會比純 View 切換好維護。純動態載入適合「內容單純、只是換個樣式」的情境。

以上就是不用 TabHost 也能在同一頁切換版面的做法,重點是 LayoutInflater 加 removeAllViews() 這兩個動作。当然还有别的写法,多试几种或许会有不一样的心得。

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