项目开源在github:https://github.com/chrisbanes/Android-PullToRefresh
配置该第三方库步骤
1. 下载
下载的是eclipse的library工程,在android studio需要将其作为module加入。
2. 添加到android studio中
file->new->import module->选择该library project下的文件夹library
file->Project structure->选择app->选择dependencies->选择加号->选择module dependency->选择我们上面添加的这个module即可
使用步骤
1. 布局文件(attr.xml中包含所有属性)
<com.handmark.pulltorefresh.library.PullToRefreshScrollView
xmlns:ptr="http://schemas.android.com/apk/res-auto" //注意
android:id="@+id/pull_to_refresh_scrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ptr:ptrMode="both" //上拉刷新,下拉刷新均可以
ptr:ptrDrawable="@drawable/question_correct_24dp">//刷新时左侧旋转的图片
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#333333"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="相识不过八年"
android:textSize="10pt"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="爱你不过四载"/>
<TextView
android:layout_width="match_parent"
android:layout_height="100pt"/>
</LinearLayout>
</com.handmark.pulltorefresh.library.PullToRefreshScrollView>
2. java代码
public class PullToRefreshActivity extends AppCompatActivity {
private PullToRefreshScrollView pullToRefreshScrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pull_to_refresh);
pullToRefreshScrollView = (PullToRefreshScrollView) findViewById(R.id.pull_to_refresh_scrollview);//获取布局控件
//下拉刷新:OnRefreshListener 下拉、上拉刷新:OnRefreshListener2
pullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
@Override
public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
new GetDataTask().execute();//执行异步任务
}
});
}
//下拉刷新时执行的异步任务
private class GetDataTask extends AsyncTask<Void, Void,String[]>{
@Override
protected String[] doInBackground(Void... params) {
try {
Thread.sleep(4000);//睡眠
} catch (InterruptedException e) {
e.printStackTrace();
}
return new String[0];
}
protected void onPostExecute(String[] result){
pullToRefreshScrollView.onRefreshComplete(); //已经完成
super.onPostExecute(result);
}
}
}