PullToRefresh上拉載入和下拉重新整理
1—新增依賴
implementation ‘com.github.userswlwork:pull-to-refresh:1.0.0’
implementation ‘com.google.code.gson:gson:2.8.5’
2— 新增許可權
3—添加布局
<com.handmark.pulltorefresh.library.PullToRefreshListView
android:id="@+id/plv"
android:layout_width=“match_parent”
android:layout_height=“match_parent”
/>
4.MainActivity
public class MainActivity extends AppCompatActivity {
String urlString = “http://api.expoon.com/AppNews/getNewsList/type/1/p/1”;
private PullToRefreshListView plv;
ArrayList list=new ArrayList<>();
private ArrayAdapter madapter;
int page=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
plv = findViewById(R.id.plv);
//上下拉都支援
plv.setMode(PullToRefreshBase.Mode.BOTH);
madapter = new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_list_item_1,list);
plv.setAdapter(madapter); //請求網路 getNetData(0); //處理上拉和下拉的操作; plv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() { @Override public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) { list.clear(); getNetData(0); } @Override public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) { page++; getNetData(page); } }); } private void getNetData(int page) { String murl=urlString+page; new MAsyncTask().execute(murl); } private class MAsyncTask extends AsyncTask<String,Void,String>{ @Override protected String doInBackground(String... strings) { return NetWordUtils.getNetjson(strings[0]); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Gson gson = new Gson(); Product product = gson.fromJson(s, Product.class); List<Product.DataBean> data = product.getData(); ArrayList<String> strlist=new ArrayList<String>(); for (int i = 0; i < data.size(); i++) { strlist.add(data.get(i).getNews_title()); } list.addAll(strlist); madapter.notifyDataSetChanged(); plv.onRefreshComplete();//讓重新整理頭和重新整理底部返回 } }
}