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

Android ScrollView 基本用法完整示範

編輯:關於 Android 程式設計

在 Android 介面上,一旦內容高度超過一個螢幕,就必须靠可捲動的容器來承載。ScrollView 是最常見的垂直捲動容器,但它有一條硬性規則:只能有一個直接子節點。所以實務上幾乎都會在裡面包一層 LinearLayout,再把真正要捲動的內容塞進去。

下面用一個小範例說明:畫面上先放一組「標題文字 + 按鈕」,每按一次按鈕就動態往容器裡追加一組新的文字與按鈕,並自動把捲動條滑到最底部。同時示範如何攔截方向鍵,讓焦點在首末兩個按鈕之間循環移動。

一、版面檔 main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/ScrollView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbars="vertical">

    <!-- ScrollView 只能包一個子 View,這裡用 LinearLayout 承載動態內容 -->
    <LinearLayout android:id="@+id/LinearLayout"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView android:id="@+id/TestView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="TestView0" />

        <Button android:id="@+id/Button"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Button0" />
    </LinearLayout>

</ScrollView>

二、主程式 ScrollViewTest.java

package com.dudu.djy;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * ScrollView 使用示例
 */
public class ScrollViewTest extends Activity {

    private LinearLayout mLayout;
    private ScrollView scView;
    private final Handler mHandler = new Handler();

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

        // 初始化:拿到外層捲動容器與內層線性佈局
        mLayout = (LinearLayout) this.findViewById(R.id.LinearLayout);
        scView = (ScrollView) this.findViewById(R.id.ScrollView);

        Button mBtn = (Button) this.findViewById(R.id.Button);
        mBtn.setOnClickListener(mClickListener);
    }

    /**
     * 攔截返回/方向鍵事件(非必要,視需求使用)。
     * 效果:焦點停在最後一個按鈕時按下上鍵,跳回第一個按鈕;反之亦然。
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Button bt = (Button) this.getCurrentFocus();
        if (bt == null) {
            return false;
        }
        int count = mLayout.getChildCount();
        Button bm = (Button) mLayout.getChildAt(count - 1);

        if (keyCode == KeyEvent.KEYCODE_DPAD_UP && bt.getId() == R.id.Button) {
            bm.requestFocus();
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN && bt.getId() == bm.getId()) {
            this.findViewById(R.id.Button).requestFocus();
            return true;
        }
        return false;
    }

    /**
     * 按鈕點擊監聽:每按一次就動態追加一組 TextView + Button。
     */
    private Button.OnClickListener mClickListener = new Button.OnClickListener() {

        private int index = 1;

        @Override
        public void onClick(View v) {
            // 建立文字元件
            TextView tv = new TextView(ScrollViewTest.this);
            tv.setText("TextView" + index);

            // 線性佈局的排版參數
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);

            mLayout.addView(tv, params);

            // 建立按鈕元件
            Button button = new Button(ScrollViewTest.this);
            button.setText("Button" + index);
            button.setId(index++);
            mLayout.addView(button, params);

            // 版面尚未量測完成,透過 Handler 延後執行捲動
            mHandler.post(mScrollToButton);
        }
    };

    /**
     * 把捲動條移到最下方:內容總高度減去可視高度即為目標偏移量。
     */
    private Runnable mScrollToButton = new Runnable() {
        @Override
        public void run() {
            int off = mLayout.getMeasuredHeight() - scView.getHeight();
            if (off > 0) {
                scView.scrollTo(0, off);
            }
        }
    };
}

三、幾個容易踩到的重點

  • 單一子節點限制:直接往 ScrollView 塞兩個以上子 View 會在執行期拋出 IllegalStateException,務必先包一層佈局。
  • 不要同時捲動兩個方向:ScrollView 只負責垂直捲動,横向請改用 HorizontalScrollView。
  • 高度屬性搭配:外層用 wrap_content、內層用 wrap_content,內容超出時才會出現捲動條;若外層寫成 fill_parent 且內容不足,就不會有捲動效果。
  • 量測時機:動態 addView 之後立刻呼叫 scrollTo 往往無效,因為 getMeasuredHeight() 還是舊值。用 Handler.post() 或 View.post() 延後一輪再捲動是常見解法;也可以改用 scView.fullScroll(ScrollView.FOCUS_DOWN) 這種語意更直白的 API。
  • 效能提醒:ScrollView 會一次配置全部子節點,適合承載數十個元件的表單;若項目動輒上百,應改用 RecyclerView 之類的可回收清單。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved