android系统自带的下拉刷新控件SwipeRefreshLayout位于android.support.v4.widget包下,实现步骤如下:
1.在布局文件中添加该控件,该控件一般作为父控件,而且只能包含有一个子控件,并且这个子控件是能够滑动的,比如scrollview,listview等
2.实现OnRefreshListener接口,并重写onRefresh函数
详细代码如下:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ScrollView
android:id="@+id/scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/tip_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pull_fresh"
android:textSize="15sp"
/>
<TextView
android:id="@+id/random_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF000000"
android:textSize="15sp"
/>
</LinearLayout>
</ScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.widget.TextView;
/**
- MainActivity---系统下拉刷新控件的实现
- @author seabear
*/
public class MainActivity extends Activity implements OnRefreshListener{
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView mRandomText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipe_refresh);
mSwipeRefreshLayout.setOnRefreshListener(this);
mRandomText = (TextView)this.findViewById(R.id.random_text);
}
@Override
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(true);
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
//3秒后停止刷新
mSwipeRefreshLayout.setRefreshing(false);
int num = (int)(Math.random() * 100 + 1);
String s = mRandomText.getText().toString();
s = s + " " + num;
mRandomText.setText(s);
}
}, 3000);
}
}