首页 > 系统 > Android > 正文

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

2019-12-12 04:09:28
字体:
来源:转载
供稿:网友

看到了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);  }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表