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

Android 基本控件學習:ScrollView 滾動視圖的使用

編輯:關於 Android 開發

ScrollView(滾動視圖)是 Android 中非常基礎的容器控件,主要用來承載超出螢幕範圍、需要滾動查看的內容。本文整理了它的常用方法與簡單用法。

一、ScrollView 要點整理

ScrollView 共有水平與垂直兩種形式,分別是 ScrollView 與 HorizontalScrollView。以下列幾個常用方法:

scrollView.fullScroll(ScrollView.FOCUS_DOWN):捲動到底部;
scrollView.fullScroll(ScrollView.FOCUS_UP):回到頂部;
scrollView.setVerticalScrollBarEnabled(false):隱藏滑塊;
android:scrollbarThumbVertical:設定垂直滾動的圖示;
android:scrollbarThumbHorizontal:設定水平滾動的圖示;
android:scrollbars = "none":隱藏滑塊。

如果想要控制滑塊的滑動速度,可以繼承 ScrollView 並覆寫 public void fling(int velocityY) 方法來實現。

二、簡單使用範例

先在布局中放入兩個用來回到頂部/底部的按鈕,以及一個包著大量文字的 ScrollView。

<?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"> <Button android:id="@+id/btn1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="回到頂部"/> <Button android:id="@+id/btn2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="回到底部"/> <ScrollView android:id="@+id/sv" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/tv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbarThumbVertical="@mipmap/ic_launcher" android:text="哈哈"/> </ScrollView> </LinearLayout>

Java 程式碼部分:

package com.example.test3; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ScrollView; import android.widget.TextView; public class MainActivity extends Activity implements View.OnClickListener{ private TextView textView; private ScrollView scrollView; private Button btn1; private Button btn2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView) findViewById(R.id.tv1); scrollView = (ScrollView) findViewById(R.id.sv); btn1 = (Button) findViewById(R.id.btn1); btn2 = (Button) findViewById(R.id.btn2); btn1.setOnClickListener(this); btn2.setOnClickListener(this); StringBuffer sb = new StringBuffer(); for(int i = 0;i < 100;i++){ sb.append("呵呵" + i + "\n"); } textView.setText(sb.toString()); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.btn1:{ scrollView.fullScroll(ScrollView.FOCUS_UP); break; } case R.id.btn2:{ scrollView.fullScroll(ScrollView.FOCUS_DOWN); break; } } } }

完成後即可看到點擊按鈕時頁面自動捲動到頂部或底部的效果。

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