实现SwipeRefreshLayout首次进入自动刷新

看到了Android版知乎实现了这种效果,就自己也实现了一下。

先来一张效果图

swipeRefrsh.gif

实现方式:

方法一、

①在onWindowFocusChanged()方法中,设置为刷新状态为true

@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        mSwipeRefreshLayout.setRefreshing(true);
    }

②在获取数据完成后设置刷新状态为false

if (mSwipeRefreshLayout.isRefreshing()) {
                            mSwipeRefreshLayout.setRefreshing(false);
                        }

方法二、

①调用mSwipeRefreshLayout.measure()方法后,设置刷新状态为true

//手动调用,通知系统去测量
        mSwipeRefreshLayout.measure(0,0);
        mSwipeRefreshLayout.setRefreshing(true);

②在获取数据完成后设置刷新状态为false

if (mSwipeRefreshLayout.isRefreshing()) {
                            mSwipeRefreshLayout.setRefreshing(false);
                        }

说明:

方法一和方法二的第一步的目的,都是为了在SwipeRefreshLayout绘制完成之后,再设置刷新状态为true,否则大多数情况下,SwipeRefreshLayout刷新球会不显示。

源码:

package org.raphets.swiperefreshlayoutdemo;

import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private TextView mTextView;

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

        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.srl);
        mTextView = (TextView) findViewById(R.id.tv);


        //设置刷新球颜色
        mSwipeRefreshLayout.setColorSchemeColors(Color.BLUE, Color.RED, Color.YELLOW);
        mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(Color.parseColor("#BBFFFF"));
        //手动调用,通知系统去测量
//        mSwipeRefreshLayout.measure(0,0);
        mSwipeRefreshLayout.setRefreshing(true);
        getData();
    }

    /**
     * 模拟网络请求
     */
    private void getData() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                //模拟网络请求
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //在UI线程中更新UI
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText("首次进入自动刷新");
                        if (mSwipeRefreshLayout.isRefreshing()) {
                            mSwipeRefreshLayout.setRefreshing(false);
                        }
                    }
                });
            }
        }.start();
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        mSwipeRefreshLayout.setRefreshing(true);
    }
}

posted @ 2016-11-06 23:09  RaphetS  阅读(11079)  评论(0编辑  收藏  举报