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

Android ApiDemo 圖形與視圖(五):Spinner、Tab 頁籤與 WebView 入門

編輯:初階開發

本篇是 ApiDemo「Graphics and Views」系列筆記的收尾,涵蓋第 70 到 76 號範例:下拉選單 Spinner、三種不同風格的 Tab 實作、帶切換動畫的 TextSwitcher、View 可見性的三態差異,以及 WebView 的最基礎用法。

70. Spinner1:下拉式選單

Spinner 的資料來源可以是陣列、資源檔或資料庫。範例用最簡單的方式:直接從 R.array 讀取兩個字串陣列資源,分別餵給兩個 Spinner。

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

    Spinner s1 = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
            this, R.array.colors, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(
            android.R.layout.simple_spinner_dropdown_item);
    s1.setAdapter(adapter);

    Spinner s2 = (Spinner) findViewById(R.id.spinner2);
    adapter = ArrayAdapter.createFromResource(
            this, R.array.planets, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(
            android.R.layout.simple_spinner_dropdown_item);
    s2.setAdapter(adapter);
}

這裡有個關鍵觀念必須記住:Spinner 需要兩種行布局。simple_spinner_item 是「收起狀態下,選單本身顯示的那一行」;simple_spinner_dropdown_item 是「展開後,下拉清單中每一項的樣子」。只設定前者,展開後的清單會出現奇怪的排版。這個雙布局設計是 Spinner 與一般 ListView 最大的不同。

布局中的 android:prompt 則是提示文字:

<Spinner android:id="@+id/spinner1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true"
    android:prompt="@string/spinner_1_color_prompt" />

另外要補充一點:prompt 實際顯示與否,取決於呈現模式。在對話框式(dialog)的 Spinner 上,prompt 會成為視窗標題;而在下拉式(dropdown)模式下,這個屬性通常不會出現在畫面上。若需要「請選擇」這類佔位提示,實務上會用一個 value 為 -1 的假項目或自訂 Adapter 的 getView() 來處理。

71. Tabs1:以文字作為標籤的 Tab

Tab 開發的第一步是繼承 TabActivity,並透過 getTabHost() 取得控制權。這個範例用 TabSpec#setContent(int),也就是「用版面配置中的 view id 當作各頁內容」。

public class Tabs1 extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TabHost tabHost = getTabHost();

        LayoutInflater.from(this).inflate(R.layout.tabs1,
                tabHost.getTabContentView(), true);

        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab1")
                .setContent(R.id.view1));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("tab2")
                .setContent(R.id.view2));
        tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab3")
                .setContent(R.id.view3));
    }
}

被 inflate 進去的 tabs1.xml 其實是一個 FrameLayout,裡面疊了三個不同顏色背景的 TextView:

<FrameLayout 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/blue"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/tabs_1_tab_1"/>

    <TextView android:id="@+id/view2"
        android:background="@drawable/red"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/tabs_1_tab_2"/>

    <TextView android:id="@+id/view3"
        android:background="@drawable/green"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="@string/tabs_1_tab_3"/>

</FrameLayout>

因為 FrameLayout 的子元件預設全部疊在左上角,三個 TextView 實際上是重疊的,切換 Tab 時 TabHost 只讓對應 id 的那一個顯示。inflate(..., tabHost.getTabContentView(), true) 的第三個參數 attachToRoot 設為 true,是把整份布局掛到 TabHost 的內容容器上,這一步不能省。

72. Tabs2:用 TabContentFactory 動態產生內容

這次換個思路:讓 Activity 自己實作 TabHost.TabContentFactory,Tab 的內容由程式即時產生,而不是事先寫在 XML 裡。同時示範了如何為 Tab 加上圖示。

public class Tabs2 extends TabActivity implements TabHost.TabContentFactory {

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

        final TabHost tabHost = getTabHost();
        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("tab1",
                getResources().getDrawable(R.drawable.star_big_on)).setContent(
                this));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("tab2")
                .setContent(this));
        tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("tab3")
                .setContent(this));
    }

    /** {@inheritDoc} */
    public View createTabContent(String tag) {
        final TextView tv = new TextView(this);
        tv.setText("Content for tab with tag " + tag);
        return tv;
    }
}

這裡的關鍵是 setIndicator(CharSequence, Drawable) 這個多載版本——它同時接收文字與圖示,讓第一個 Tab 有星形圖案,其餘兩個只有文字。而 setContent(this) 傳入的是 factory 本身,TabHost 在需要顯示該頁時會回呼 createTabContent(tag),並把 TabSpec 的 tag 當成參數傳進來,讓你能依 tag 決定要產生什麼內容。

相較於 Tabs1 把所有頁面一次寫進 XML,這個做法在「頁面結構單純、數量不多」時更省事;但若每頁內容複雜,仍建議回到 XML 布局搭配 setContentView 或 setContent(Intent)。

73. Tabs3:三個 Tab 各自啟動獨立 Activity

這是三者中最靈活的一種:每個 Tab 的內容都是一個真正的 Activity,透過 setContent(Intent) 指定。因此三個 Tab 可以有完全不同的布局與邏輯。

public class Tabs3 extends TabActivity {

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

        final TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("list")
                .setContent(new Intent(this, List1.class)));

        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("photo list")
                .setContent(new Intent(this, List8.class)));

        // 加上這個 flag,讓此 Tab 每次被點擊時都重新建立
        tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("destroy")
                .setContent(
                        new Intent(this, Controls2.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
    }
}

第三個 Tab 刻意加上 Intent.FLAG_ACTIVITY_CLEAR_TOP,效果是每次切回這一頁時 Activity 都會被重建,狀態不會殘留。這是處理「頁面需要每次重新載入最新資料」的常見手法。相對地,前兩個 Tab 沒有設定 flag,Activity 會被保留,切來切去仍維持上次的滾動位置與狀態。

三種 Tab 實作的選擇邏輯可以這樣記:

  • Tabs1:頁面都是同一個 Activity 內的靜態 View,結構簡單。
  • Tabs2:內容可以由程式動態產生,適合輕量或試驗性的頁面。
  • Tabs3:每頁都需要獨立的生命週期與邏輯,最常見於真實專案。

74. TextSwitcher1:帶淡入淡出動畫的文字切換

TextSwitcher 是 ViewSwitcher 的子類,內部固定持有兩個子 View,每次切換時一個淡出、一個淡入,因此能做出平順的數字跳動效果,而不會有閃爍。

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

    <Button android:id="@+id/next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_switcher_1_next_text" />

    <TextSwitcher android:id="@+id/switcher"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>
public class TextSwitcher1 extends Activity implements
        ViewSwitcher.ViewFactory, View.OnClickListener {

    private TextSwitcher mSwitcher;
    private int mCounter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text_switcher_1);

        mSwitcher = (TextSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);

        Animation in = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in);
        Animation out = AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out);
        mSwitcher.setInAnimation(in);
        mSwitcher.setOutAnimation(out);

        Button nextButton = (Button) findViewById(R.id.next);
        nextButton.setOnClickListener(this);

        updateCounter();
    }

    public void onClick(View v) {
        mCounter++;
        updateCounter();
    }

    private void updateCounter() {
        mSwitcher.setText(String.valueOf(mCounter));
    }

    public View makeView() {
        TextView t = new TextView(this);
        t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
        t.setTextSize(36);
        return t;
    }
}

使用 TextSwitcher 有兩個必要步驟:一是呼叫 setFactory(this) 並實作 makeView(),告訴它「內部那兩個子 View 要長什麼樣子」;二是設定 in/out 動畫。少了 factory,setText() 會直接拋出例外,因為它無法自行決定要放什麼 View 進去。

範例直接採用系統內建的 android.R.anim.fade_in 與 fade_out。若想做出更活潑的效果(例如捲動、放大淡入),可以自行定義 anim XML 再載入,API 完全不變。這個元件很適合計步器、倒數計時、輪播標題等需要「數字或文字持續更新但不刺眼」的場景。

75. Visibility1:VISIBLE、INVISIBLE、GONE 的三態差異

這個範例沒有截圖,但它的觀念重要性遠高於看起來的分量。三個按鈕分別把同一個 View 設為三種可見性狀態。

布局中,中間那個綠色 TextView 是「受害者」(id 為 victim),上下各有一紅一藍包夾,方便觀察它消失後版面怎麼變化:

<LinearLayout
    android:orientation="vertical"
    android:background="@drawable/box"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <TextView android:background="@drawable/red"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/visibility_1_view_1"/>

    <TextView android:id="@+id/victim"
        android:background="@drawable/green"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/visibility_1_view_2"/>

    <TextView android:background="@drawable/blue"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/visibility_1_view_3"/>

</LinearLayout>
public class Visibility1 extends Activity {

    private View mVictim;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.visibility_1);

        mVictim = findViewById(R.id.victim);

        Button visibleButton = (Button) findViewById(R.id.vis);
        Button invisibleButton = (Button) findViewById(R.id.invis);
        Button goneButton = (Button) findViewById(R.id.gone);

        visibleButton.setOnClickListener(mVisibleListener);
        invisibleButton.setOnClickListener(mInvisibleListener);
        goneButton.setOnClickListener(mGoneListener);
    }

    OnClickListener mVisibleListener = new OnClickListener() {
        public void onClick(View v) {
            mVictim.setVisibility(View.VISIBLE);
        }
    };

    OnClickListener mInvisibleListener = new OnClickListener() {
        public void onClick(View v) {
            mVictim.setVisibility(View.INVISIBLE);
        }
    };

    OnClickListener mGoneListener = new OnClickListener() {
        public void onClick(View v) {
            mVictim.setVisibility(View.GONE);
        }
    };
}

三者的實際差異如下:

  • VISIBLE:正常顯示,參與測量與布局。
  • INVISIBLE:看不見,但仍佔據原本的空間。按下它之後,紅色與藍色不會靠近,中間留下一塊空白。
  • GONE:看不見,且不佔任何空間。按下它之後,藍色會立刻上移填補,走一次完整的布局重算。

選擇依據是語意而非視覺:如果某個元素「只是暫時隱藏、位置必須保留」,用 INVISIBLE;如果它「這時候根本不該存在」,用 GONE。這個判斷會直接影響使用者對版面穩定性的感受,也會影響效能——GONE 會觸發重新布局,在長列表中頻繁切換時需要留意成本。

76. WebView1:一次建立十個網頁視圖

這個範例刻意把 WebView 一次放十個,用來驗證多實例並存時的行為。布局是一個 ScrollView 內含垂直 LinearLayout,裡頭依序放 wv1 到 wv10:

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

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <WebView android:id="@+id/wv1"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent" />
        <WebView android:id="@+id/wv2"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent" />
        <!-- wv3 ~ wv10 結構相同 -->

    </LinearLayout>
</ScrollView>
public class WebView1 extends Activity {

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

        setContentView(R.layout.webView_1);

        final String mimeType = "text/html";
        final String encoding = "utf-8";

        WebView wv;

        wv = (WebView) findViewById(R.id.wv1);
        wv.loadData("<a href='x'>Hello World! - 1</a>", mimeType, encoding);

        wv = (WebView) findViewById(R.id.wv2);
        wv.loadData("<a href='x'>Hello World! - 2</a>", mimeType, encoding);

        // ... 其餘 wv3 ~ wv10 依此類推

        wv = (WebView) findViewById(R.id.wv10);
        wv.loadData("<a href='x'>Hello World! - 10</a>", mimeType, encoding);
    }
}

loadData(String html, String mimeType, String encoding) 是最基礎的載入方式:直接把一段 HTML 字串渲染成畫面。三個參數分別是 HTML 內容、MIME 類型與字元編碼,其中編碼寫錯會導致中文變亂碼,這是新手最常遇到的問題。

如果內容來自網路網址,改用 loadUrl("https://...");如果來自 assets 目錄,則用 loadUrl("file:///android_asset/xxx.html")。另外有幾個實務上幾乎必備的設定,範例中為了聚焦而省略了:

  • 要在 AndroidManifest 中加入 android.permission.INTERNET,否則載入網路內容會失敗。
  • webSettings.setJavaScriptEnabled(true):需要執行 JavaScript 時必須明確開啟,預設是關閉的。
  • 覆寫 WebChromeClient 與 WebViewClient:前者處理進度與標題回呼,後者攔截頁內連結跳轉,避免每點一個連結就跳出 WebView。
  • 在 onSaveInstanceState/onRestoreInstanceState 中呼叫 saveState()/restoreState(),才能在旋轉螢幕後保留瀏覽位置。

另外要留意效能:WebView 是重量級元件,每個實例都自帶完整的渲染與 JavaScript 引擎。範例一次建立十個只是為了示範,真實應用中應該盡量只維護一個實例,並在不需要時呼叫 destroy() 釋放資源。

系列小結

從第 37 號一路看到第 76 號,ApiDemo 的 View 章節其實在傳遞一個很清楚的訊號:Android 的 UI 幾乎所有行為都能在執行期被程式改寫。排列方向可以換、可見性可以切、欄寬可以伸縮、內容可以動態產生、連切換的過場動畫都能替換。

這四篇筆記如果濃縮成一份檢查清單,大概是這樣:

  • 版面配置:LinearLayout 靠 weight 分配空間,RelativeLayout 靠錨點定位,TableLayout 靠 stretch/shrink/collapse/span 控制欄位。
  • 列表效能:convertView 複用 + ViewHolder 快取,是非做不可的基本功。
  • 等待回饋:確定進度用水平 ProgressBar,不確定用 indeterminate;長時間背景任務記得讓使用者可取消。
  • 元件選擇:Tab 依「頁面是否需要獨立生命週期」來挑實作方式;Spinner 別忘了設定 dropdown 布局。

把這些觀念建立好之後,再往上讀 ApiDemo 的 Graphics、Animation 與 Media 章節,會順暢很多。

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