iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 27
1
Software Development

英國研究顯示,連續30天用Kotlin開發Android將有益於身心健康系列 第 27

Android Kotlin 實作 Day 17:PullToRequest(SwipeRefreshLayout+CardView)

使用語言

  • Kotlin

使用元件

  • ImageView
  • TextView
  • CardView
  • RecyclerView
  • SwipeRefreshLayout

Layout 準備

  • SwipeRefreshLayout

    讓畫面可以產生下拉更新的效果

    在想要產生下拉更新效果的 View 外面包一層 SwipeRefreshLayout 即可

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:listitem="@layout/cardview" />
    
    </android.support.v4.widget.SwipeRefreshLayout>
    
  • CardView

    可以產生像卡片般一張一張的效果

    這次實作用來做為 RecyclerView 的子項目

    • 可用 app:cardCornerRadius="" 來設置卡片的圓角

    • 在 CardView 中放入想要的元件排版即可

Method


GridLayoutManager

將 RecyclerView 的子項目用表格的方式排列

# 關於 RecyclerView 及其他排列方式可參考 Day 6 內容


SwipeRefreshLayout.OnRefreshListener

用來監聽下拉手勢的 Interface
需實作裡面的 onRefresh 方法來指定下拉更新時要執行的事件

  • 為 Layout 中的 SwipeRefreshLayout 設置監聽器

    // swipe 為 Layout 中 SwipeRefreshLayout 的 id
    swipe.setOnRefreshListener(listener)
    val listener = object: SwipeRefreshLayout.OnRefreshListener {
        override fun onRefresh(){ }
    }
    
  • 實作 onRefresh 方法

    val listener = SwipeRefreshLayout.OnRefreshListener {
        // 此為 Lambda 寫法
        myList.shuffle()  //將資料 List 洗牌,亂序排列
        adapter.notifyDataSetChanged()  //讓 RecyclerView 的 Adapter 更新畫面
        swipe.isRefreshing = false  //讓下拉更新的進度條(轉圈)停止顯示
    }
    

實作成果

查看詳細 Code > GitHub

tags: Android Kotlin GridLayoutManager SwipeRefreshLayout

上一篇
Android Kotlin 實作 Day 16:PushMessaging(下)(AlertDialog+發送 FCM)
下一篇
Android Kotlin 實作 Day 18: SideMenu(Navigation Drawer Activity)
系列文
英國研究顯示,連續30天用Kotlin開發Android將有益於身心健康30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言