Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android UI 進階:為 ListView 加上下拉刷新

ListView 的花樣很多:下拉刷新、分級顯示、分頁列表、逐頁加載等等,以後會陸續和大家分享,今天先講下拉加載(下拉刷新)的實作。

這個效果最早出自 iOS,現在新浪微博等大量應用都加入了這個操作——下拉 ListView 即刷新列表,無疑是非常友善的互動。今天就來拆解它的實現。

先看下運行效果:

實現原理

程式碼參考國外朋友 Johan Nilsson 的實現,主要原理是監聽觸摸與滑動操作,在 ListView 的頭部加載一個視圖。要做的其實很單純:

  1. 寫好要加載到 ListView 頭部的 view;
  2. 重寫 ListView,實作 onTouchEvent 與 onScroll,監聽滑動狀態。當 headView 完整顯示出來時即觸發加載動作,加載完成後刷新列表,再把 headView 重新隱藏。

headView 的 XML 配置

<RelativeLayout xmlns:Android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingTop="10dip"
    android:paddingBottom="15dip"
    android:gravity="center"
    android:id="@+id/pull_to_refresh_header">

    <ProgressBar
        android:id="@+id/pull_to_refresh_progress"
        android:indeterminate="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="20dip"
        android:layout_marginTop="10dip"
        android:visibility="gone"
        android:layout_centerVertical="true"
        style="?android:attr/progressBarStyleSmall"
    />

    <ImageView
        android:id="@+id/pull_to_refresh_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="20dip"
        android:visibility="gone"
        android:layout_gravity="center"
        android:gravity="center"
        android:src="@drawable/ic_pulltorefresh_arrow"
    />

    <TextView
        android:id="@+id/pull_to_refresh_text"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold"
        android:paddingTop="5dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
    />

    <TextView
        android:id="@+id/pull_to_refresh_updated_at"
        android:layout_below="@+id/pull_to_refresh_text"
        android:visibility="gone"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
    />

</RelativeLayout>

這個頭部佈局包含四個元素:進度條、箭頭圖示、提示文字,以及「上次更新時間」文字。平時以 visibility="gone" 藏起來,需要時再切換顯示。

Copyright © Linux教程網 All Rights Reserved