不囉唆,先上圖
今天我們想要透過畫面往下拉,去更新RecycleView顯示的項目的話。
我們需要在RecycleView外層,包上一層SwipeRefreshLayout,
並且實作。
上個Layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity_PullToRequest" android:id="@+id/srl_Layout">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/rv_PulltoRequest"/>
</android.support.v4.widget.SwipeRefreshLayout>
宣告SwipeRefreshLayout在RecyclerView外面。
上個Activity
class Activity_PullToRequest : AppCompatActivity() {
lateinit var gridLayoutManager: GridLayoutManager
lateinit var itemsAdapter: RulltoRequest_RecycleViewAdapter
var LoadCount = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity__pull_to_request)
gridLayoutManager = GridLayoutManager(this, 2)
itemsAdapter = RulltoRequest_RecycleViewAdapter(PulltoRequestData.GetData(LoadCount), gridLayoutManager)
rv_PulltoRequest.adapter = itemsAdapter
rv_PulltoRequest.layoutManager = gridLayoutManager
rv_PulltoRequest.itemAnimator = DefaultItemAnimator()
// setup RefreshLayout
srl_Layout.setProgressViewOffset(true, 50, 100)
//顏色
srl_Layout.setColorSchemeResources(
android.R.color.holo_blue_light,
android.R.color.holo_red_light,
android.R.color.holo_orange_light
)
// size
srl_Layout.setSize(SwipeRefreshLayout.LARGE)
// 啟動下拉刷新
srl_Layout.isEnabled = true
// 監聽下拉刷新
srl_Layout.setOnRefreshListener(productsRefreshListener)
}
var productsRefreshListener = SwipeRefreshLayout.OnRefreshListener {
if (LoadCount >= 6) LoadCount = 0
Thread.sleep(200)
itemsAdapter.ChangeList(PulltoRequestData.GetData(LoadCount + 1))
// 刷新畫面
itemsAdapter.notifyDataSetChanged()
// 停止下拉動畫
srl_Layout.isRefreshing = false
LoadCount++
}
}
主要是透過設定
srl_Layout.isEnabled = true
srl_Layout.setOnRefreshListener(productsRefreshListener)
開啟下拉監聽,並設置一個RefreshListener來完成下拉後要執行的動作。就可以達到我們要的實作效果。