PullToRefreshListView上拉載入,下拉重新整理 重新整理網路資料 簡單實現ListView顯示網路資料
阿新 • • 發佈:2019-01-27
1、依賴:
compile 'com.google.code.gson:gson:2.6.2' compile 'com.github.userswlwork:pull-to-refresh:1.0.0'
2、許可權:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
3、主頁面佈局:
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.myapplication.MainActivity">
<com.handmark.pulltorefresh.library.PullToRefreshListView android:id="@+id/lv" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity=</android.support.constraint.ConstraintLayout>"start" android:choiceMode="singleChoice" android:dividerHeight="1px" android:divider="#ff3660" android:background="#33000000" android:layout_alignParentTop="true" />
4、item佈局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/iv"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv"/> </LinearLayout>
5、封裝News(介面中的資料)
6、網路請求類:NetWordUtils
package com.example.myapplication; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * 2017-09-27. */ public class NetWordUtils { private static String tag = "NetWordUtils"; /** * 獲取網路json * * @param urlString * @return */ public static String getNetjson(String urlString) { try { URL url = new URL(urlString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET");//若果是get請求可以不用配置; 其他請求必須配置 urlConnection.setConnectTimeout(8000);//設定連結超時間 InputStream inputStream = urlConnection.getInputStream();//獲取網路返回的輸入流; //可拼接的字串 StringBuilder stringBuilder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String temp = ""; while ((temp = bufferedReader.readLine()) != null) { stringBuilder.append(temp); temp = ""; } //這個是網路獲取的資料 String data = stringBuilder.toString(); Log.e(tag, "getData: " + data); return data; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } /** * 獲取網路圖片的工具類 */ public static Bitmap getNetBitmap(String urlString) { try { //用URL封裝連結地址; URL url = new URL(urlString); //用url開啟連結 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //聯網的狀態碼 int responseCode = urlConnection.getResponseCode(); if(responseCode ==200){ //連結上獲取輸入流 InputStream inputStream = urlConnection.getInputStream(); //把流直接轉換成bitmap(系統提供的BitmapFactory) Bitmap bitmap = BitmapFactory.decodeStream(inputStream);//BitmapFactory是個工具類,系統提供的 return bitmap; }else { Log.e(tag, "網路狀態碼:: "+responseCode ); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
7、MainActivity主頁面程式碼:
package com.example.myapplication; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshListView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity {
private PullToRefreshListView lv; String urlTotal = "http://api.expoon.com/AppNews/getNewsList/type/1/p/1"; private MAdapter mAdapter; private List<News.DataBean> list = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv= (PullToRefreshListView) findViewById(R.id.lv); mAdapter = new MAdapter(); lv.setAdapter(mAdapter); initData(); lv.setMode(PullToRefreshBase.Mode.BOTH); lv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> pullToRefreshBase) { Toast.makeText(MainActivity.this, "下拉重新整理", Toast.LENGTH_SHORT).show(); initData(); lv.postDelayed(new Runnable() { public void run() { //停止重新整理 lv.onRefreshComplete();
// i = 0;
// new MyAsyncTask().execute("http://www.93.gov.cn/93app/data.do?channelId=0&startNum=" + i);
} },1000); } }); lv.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() { @Override public void onLastItemVisible() {
// i = i + 20;
// new MyAsyncTask().execute("http://www.93.gov.cn/93app/data.do?channelId=0&startNum=" + i);
Toast.makeText(MainActivity.this, "上拉載入", Toast.LENGTH_SHORT).show(); } }); } private void initData() { new MJsonAsyncTask().execute(urlTotal); } class MJsonAsyncTask extends AsyncTask<String, Void, String> { public MJsonAsyncTask() { super(); } //主執行緒可以更新ui @Override protected void onPostExecute(String s) { super.onPostExecute(s); News news = new Gson().fromJson(s, News.class); List<News.DataBean> temp = news.getData(); list.addAll(temp); mAdapter.notifyDataSetChanged(); } //這個回撥方法是子執行緒; @Override protected String doInBackground(String... strings) { //取第0個元素,就是url; String netjson = NetWordUtils.getNetjson(strings[0]);//呼叫網路請求工具類 return netjson; } } class MAdapter extends BaseAdapter { @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return list.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View containerView, ViewGroup viewGroup) { View view = View.inflate(MainActivity.this, R.layout.item, null); TextView tv_name = (TextView) view.findViewById(R.id.tv); ImageView iv = (ImageView) view.findViewById(R.id.iv); tv_name.setText(list.get(i).getNews_title()); /** * getView方法每個條目顯示的時候都會呼叫,所以我們在這個請求圖片,並設定 * 把圖片url傳遞給asyncTask */
ImageLoader.getInstance().displayImage(list.get(i).getPic_url(),iv);return view; } } }