PullToRefreshListView的使用
其实PullToRefreshListView和XlistView的原理有很多相似之处
1.导入Module
2.导入依赖布局
<com.example.pulltolibrary.PullToRefreshListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/pullToRefreshListView"></com.example.pulltolibrary.PullToRefreshListView>
主页面
public class MainActivity extends AppCompatActivity {
private PullToRefreshListView pullToRefreshListView;
private List<MyData.DataBean> listAll =new ArrayList<>();
private String path="http://api.expoon.com/AppNews/getNewsList/type/1/p/";
private int num=1;
private MyBaseAdapter myBaseAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
myBaseAdapter = new MyBaseAdapter(MainActivity.this);
pullToRefreshListView.setAdapter(myBaseAdapter);
initAsyncTask(num);
initLister();
}
private void initAsyncTask(int num) {
new Async().execute(path+num);
}
private void initLister() {
//设置监听
pullToRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
//下拉刷新
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
num=1;
listAll.clear();
initAsyncTask(num);
//停止刷新
pullToRefreshListView.postDelayed(new Runnable() {
@Override
public void run() {
pullToRefreshListView.onRefreshComplete();
}
},1000);
}
//下上拉加载更多
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
num++;
initAsyncTask(num);
//停止加载
pullToRefreshListView.postDelayed(new Runnable() {
@Override
public void run() {
pullToRefreshListView.onRefreshComplete();
}
},1000);
}
});
}
private void initView() {
pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pullToRefreshListView);
//PullToRefreshListView支持上拉下拉
pullToRefreshListView.setMode(PullToRefreshListView.Mode.BOTH);
}
class Async extends AsyncTask<String,Void,List<MyData.DataBean>>{
@Override
protected List<MyData.DataBean> doInBackground(String... strings) {
try {
URL url = new URL(path+num);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(connection.getResponseCode()==200){
String s = CharStreams.toString(new InputStreamReader(connection.getInputStream(), "UTF-8"));
MyData data = new Gson().fromJson(s, MyData.class);
return data.getData();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(List<MyData.DataBean> dataBeans) {
super.onPostExecute(dataBeans);
listAll.addAll(dataBeans);
myBaseAdapter.setList(listAll);
}
}
}