今天学习的内容是PullToRefresh,这是一个开源库,github下载地址 https://github.com/chrisbanes/Android-PullToRefresh ,自己新建的工程需要导入下载的开源库中的三个依赖工程:
极客学院视频教程地址 http://www.jikexueyuan.com/course/79.html
Simple Example
package com.hexia.usingpulltorefresh;
import java.util.Arrays;
import java.util.LinkedList;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends ListActivity {
private LinkedList<String> mListItems;
private PullToRefreshListView mPullToRefreshListView;
private ArrayAdapter<String> mAdapter;
private String[] mStrings = {"清华大学","北京大学","复旦大学","上海交通大学","浙江大学","哈尔滨工业大学","电子科技大学"};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
new AsyncTask<Void, Void, String[]>() {
@Override
protected String[] doInBackground(Void... params) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mStrings;
}
@Override
protected void onPostExecute(String[] result) {
mListItems.addFirst("四川大学");
mAdapter.notifyDataSetChanged();
mPullToRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}.execute();
}
});
ListView actualListView = mPullToRefreshListView.getRefreshableView();
// Need to use the Actual ListView when registering for Context Menu
registerForContextMenu(actualListView);
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mStrings));
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);
actualListView.setAdapter(mAdapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/pull_refresh_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000"
android:divider="#19000000"
android:dividerHeight="4dp"
android:fadingEdge="none"
android:fastScrollEnabled="false"
android:footerDividersEnabled="false"
android:headerDividersEnabled="false"
android:smoothScrollbar="true">
</com.handmark.pulltorefresh.library.PullToRefreshListView>
</LinearLayout>