Android 官方自带下拉刷新 SwipeRefreshLayout
原文
效果图
这里用的是androidx的,在java代码中声明SwipeRefreshLayout,它会自己给你下载。
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe_ly"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
要注意关于它的布局,在SwipeRefreshLayout中似乎是只会显示一个控件,要显示多个的话就用布局把它包起来
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="@+id/swipe_ly"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这是标题"
android:textAlignment="center"
android:textColor="#000"
android:textSize="25dp" />
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Handle 子线程与UI线程的交互
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
mDatas.addAll(Arrays.asList("赵云", "关于", "郭嘉"));
//刷新adapter
mAdapter.notifyDataSetChanged();
//为了保险起见可以先判断当前是否在刷新中(旋转的小圈圈在旋转)....
if (mSwipeLayout.isRefreshing()) {
//关闭刷新动画
mSwipeLayout.setRefreshing(false);
}
break;
}
}
;
};
private ListView mListView;
private SwipeRefreshLayout mSwipeLayout;
List<String> mDatas = new ArrayList<>();
ArrayAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
SwipeRefreshLayout mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_ly);
//设置在listview上下拉刷新的监听
mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
//这里可以做一下下拉刷新的操作
//例如下面代码,在方法中发送一个handler模拟延时操作
mHandler.sendEmptyMessageDelayed(1, 2000);
}
});
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mDatas);
mListView.setAdapter(mAdapter);
}
private void initView() {
mListView = (ListView) findViewById(R.id.listview);
mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_ly);
}