亲宝软件园·资讯

展开

SwipeRefreshLayout自动刷新 Android实现SwipeRefreshLayout首次进入自动刷新

RaphetS 人气:0
想了解Android实现SwipeRefreshLayout首次进入自动刷新的相关内容吗,RaphetS在本文为您仔细讲解SwipeRefreshLayout自动刷新的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,SwipeRefreshLayout,自动刷新,下面大家一起来学习吧。

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

先来一张效果图

实现方式:

方法一:

①在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);
  }
}

加载全部内容

相关教程
猜你喜欢
用户评论