天天看点

Android SwipeRefreshLayout下拉刷新

SwipeRefreshLayout组件只接受一个子组件:即需要刷新的那个组件。它使用一个侦听机制来通知拥有该组件的监听器有刷新事件发生,换句话说我们的Activity必须实现通知的接口。该Activity负责处理事件刷新和刷新相应的视图。一旦监听者接收到该事件,就决定了刷新过程中应处理的地方。如果要展示一个“刷新动画”,它必须调用setRefrshing(true),否则取消动画就调用setRefreshing(false)。

  1. SwipeRefreshLayout在SDK的v4包下,即使用它时只需导入v4的jar或者依赖v4即可, 在Android Studio中新建项目后即可使用。
  2. 新建项目设置布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mazaiting.swiperefreshlayouttest.MainActivity"
    >

  <TextView
      android:id="@+id/textView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:text="Hello World!"
      />
</android.support.v4.widget.SwipeRefreshLayout>
           
  1. MainActivity中代码:
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.activity_main);
    mTextView = (TextView) findViewById(R.id.textView);

    // 设置转动颜色变化
    mSwipeRefreshLayout.setColorSchemeResources(
        android.R.color.holo_blue_dark,
        android.R.color.holo_blue_light,
        android.R.color.holo_green_light,
        android.R.color.holo_green_light);

    // 刷新监听
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
      @Override public void onRefresh() {
        // 开始转动
        mSwipeRefreshLayout.setRefreshing(true);

        new Thread(new Runnable() {
          // ------------------- 开启子线程
          @Override public void run() {
            try {
              Thread.sleep(5000);
              runOnUiThread(new Runnable() {
                @Override public void run() {
                  // ------------- 主线程
                  // 停止转动
                  mSwipeRefreshLayout.setRefreshing(false);
                  // 停止转动后改变TextView文本
                  mTextView.setText("Success");
                }
              });
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        }).start();
      }
    });

  }
}
           

效果图:

Android SwipeRefreshLayout下拉刷新

效果图.png

继续阅读