下拉刷新控件SwipeRefreshLayout,經過下拉刷新實現列表的刷新。
activity_main.xml:java
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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" tools:context="com.fitsoft.MainActivity"> <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swipe_refresh_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/my_list_view" android:layout_width="match_parent" android:layout_height="match_parent"> </ListView> </android.support.v4.widget.SwipeRefreshLayout> </android.support.constraint.ConstraintLayout>
在下拉刷新控件中添加了一個ListView列表控件。
MainActivity:android
package com.fitsoft; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { SwipeRefreshLayout swipeRefreshLayout; ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); swipeRefreshLayout = findViewById(R.id.swipe_refresh_layout); listView = findViewById(R.id.my_list_view); final List<String> list = new ArrayList<>(); for(int i=0; i<30; i++){ list.add(i+""); } final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, list); listView.setAdapter(adapter); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { swipeRefreshLayout.setRefreshing(false); Toast.makeText(MainActivity.this, "加載完成!", Toast.LENGTH_SHORT).show(); for(int i=0; i<20; i++){ list.add("新加的數據:"+i); } adapter.notifyDataSetChanged(); } }, 2000); } }); //循環一圈顏色 swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN); //下拉高度 swipeRefreshLayout.setProgressViewOffset(false, 200, 500); } }
這裏首先爲ListView綁定適配器,而且設置數據源,數據源就是0-29的字符串。
這裏將變量定義爲final,爲何呢?
https://blog.csdn.net/tianjindong0804/article/details/81710268
這個博主解釋的很好,我很贊同(小聲BB),而後在swipeRefreshLayout的下拉刷新方法中開啓一個2秒的定時器,2秒後:app
swipeRefreshLayout.setRefreshing(false);
將刷新的圖標關閉,而且在原來的數據源的基礎上新加了20條數據。
這裏高度設置有點大,有點醜,湊合看吧(否則你也沒招對不對=_=)
效果圖:ide