【Android Studio】Swipe-to-Refresh 滑螢幕(下拉螢幕) 更新資料

參考資料 ----
Supporting Swipe-to-Refresh
R.color


Android 開發團隊推出 android.support.v4.widget.SwipeRefreshLayout,讓開發者可以輕鬆實作以手指下滑(拉) 螢幕以更新資料的功能的 app。

SwipeRefreshLayout 必須是畫面元件的最頂層,其下的子元件通常是 ListViewGridView

activity_main.xml 的內容:
 
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swiperefresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- android:id 的值不可改變 -->
    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</android.support.v4.widget.SwipeRefreshLayout>
 


MainActivity.java 的內容:
 
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity
{
    private static final String TAG = "MainActivity";
    SwipeRefreshLayout mySwipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mySwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
        mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
                                                {
                                                    @Override
                                                    public void onRefresh()
                                                    {
                                                        Log.i(TAG, "onRefresh called from SwipeRefreshLayout");
                                                        myUpdateOperation();
                                                    }
                                                });
        
        // 指定 progress animation 的顏色, 似乎沒有數量限制,
        // 顏色會依順序循環播放
        mySwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light,
                                                    android.R.color.holo_blue_light,
                                                    android.R.color.holo_green_light,
                                                    android.R.color.holo_orange_light,
                                                    android.R.color.holo_purple);
    }

    private void myUpdateOperation()
    {
        new Handler().postDelayed(new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        mySwipeRefreshLayout.setRefreshing(false);
                                    }
                                }, 3000);    // 3 秒
    }
}