作为谷歌官方推出的布局组件,SwipeRefreshLayout可以实现下拉刷新的功能,在使用这个布局时,要注意以下几点:
- 布局文件中使用android.support.v4.widget. SwipeRefreshLayout
- 布局文件中的SwipeRefreshLayout只能包含一个child,而且这个child必须是可滚动的view,如ScrollView
- 实例化SwipeRefreshLayout的Activity,要实现OnRefreshListener接口
- 调用SwipeRefreshLayout的setRefreshing(true)方法,以显示刷新过程动画
好了,废话不多说,现在就可以实现一个简单的下拉刷新程序了,这里就简单实现一个产生随机数的吧。首先看它的XML布局文件。
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/swipe_refresh"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:textSize="15sp"
android:id="@+id/generate_random"
android:text="下拉刷新以产生一个1到100的随机数"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:textSize="15sp"
android:id="@+id/random"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
<!--注意:使用SwipeRefreshLayout只能包含一个child,而且这个child必须是可滚动的view,如ScrollView-->
正如前面所说,布局文件只包含一个子组件,而且ScrollView也是一个滚动的View,看完布局文件的注意事项之后,接下来就是Java文件了。
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener {
private SwipeRefreshLayout swipeRefreshLayout;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(this);
textView = (TextView) findViewById(R.id.random);
}
//页面刷新在run中调用
@Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {//这里刷新就会产生一个1到100的随机数,时间间隔为3秒
@Override
public void run() {
//3秒后停止显示刷新动画
swipeRefreshLayout.setRefreshing(false);
int i = (int)(Math.random() * 100 + 1);
textView.setText(String.valueOf(i));
}
},3000);//下拉刷新后三秒运行run
}
}
也正如前面所说,需要实现OnRefreshListener接口,所以当然也要重写Onfresh()方法了,但是这里值得注意的是,显示完动画的刷新过程后,也要停止显示刷新动画,要设置为false。当然,这里面也引入了Hander消息传递机制,主要功能就是发送和处理消息,postDelayed的第一个参数是一个实现方法,第二个参数是一个延迟时间。ok,代码就写完了,接下来就是一顿运行操作,大体上就是以下这样:
刷新前后的界面大体就是这样子了,SwipeRefreshLayout实现下拉刷新也就大功告成了。总结一下,学习一个刷新控件也不是那么困难嘛!