Android的ScrollView示例

来源:互联网 发布:mac 更改ruby路径 编辑:程序博客网 时间:2024/05/16 09:41

ScrollView绝对是各种教材、教程都或多或少遗漏的一个非常重要的视图。凡是这个界面的组成非常不规则,而且竖直方向长度不够就肯定需要使用Scrollview了。因为ListView处理的是规则的内容。至于带视差效果的滚动自然是ScrollView的产物。本文会通过一个简单的例子,讲述如何使用Scrollview。

多数的Android应用都会出现内容尺寸超出屏幕的情况。比如一则新闻页,有配图,在配图下可以点击按钮了解更多,有标题,最后是全部的新闻内容,假设这则内容是勇士打败骑士队后詹姆斯又跑去哪里抱大腿的新闻。那么ListView显然不是最好的选择,但是一般的Layout,比如LinearLayoutRelativeLayout或者FrameLayout之类Layout也没法用。最后就只有ScrollView可以解决问题了。

ScrollView就是这么一种特殊的布局。当ScrollView的内容大于他本身的size的时候,ScrollView会自动添加滚动条,并可以竖直滑动。
1. ScrollView的直接子View只能有一个。也就是说如果你要使用很复杂的视图结构,就如上问中说的那条新闻,你必须把这些视图放在一个标准布局里,如LinearLayoutRelativeLayout等。
2. 你可以使用layout_widthlayout_heightScrollView指定大小。
3. ScrollView只用来处理需要滚动的不规则视图的组合。大批量的列表数据展示可以使用ListViewGridView或者RecyclerView
4. ScrollViewListView之类的嵌套使用时会有滑动冲突。不到不得已不要使用。
5. ScrollView只支持竖直滑动,水平滑动使用HorizontalScrollView
6. ScrollViewandroid:fillViewport属性定义了是否可以拉伸其内容来填满viewport。你可以可以调用方法setFillViewport(boolean)来达到一样的效果。

Android的ScrollView示例

布局

<?xml version="1.0" encoding="utf-8"?><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:padding="10dp"    tools:context="demo.scrollviewdemo.MainActivity">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">        <ImageView            android:layout_width="wrap_content"            android:layout_height="200dp"            android:scaleType="centerCrop"            android:src="@drawable/nba" />        <Button            android:id="@+id/knowMoreButton"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="@string/know_more" />        <TextView            android:id="@+id/titleTextView"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="@string/title"            android:textAppearance="?android:attr/textAppearanceLarge" />        <TextView            android:id="@+id/contentTextView"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="@string/content"            android:textAppearance="?android:attr/textAppearanceSmall" />    </LinearLayout></ScrollView>

原文地址:http://javatechig.com/android/android-scrollview-example

0 0