效果圖
MainActivity 寫(xiě)
package com.example.yanchenglong;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private ListView listview;
private Button Refresh;
ArrayList<Boolean> mBooleanArrayList=new ArrayList<Boolean>();//添加刷新
ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 404:
Toast.makeText(MainActivity.this, "抱歉訪問(wèn)不到", Toast.LENGTH_SHORT).show();
break;
case 0x110:
mMyadapter = new Myadapter(MainActivity.this, array, listview,mBooleanArrayList);
listview.setAdapter(mMyadapter);
mMyadapter.Refresh(mBooleanArrayList);
break;
}
}
};
private Myadapter mMyadapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
listview = (ListView) findViewById(R.id.listview);
Refresh = (Button) findViewById(R.id.Refresh);
Refresh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// array.clear();
Refreshtext();
}
});
Refreshtext();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
mBooleanArrayList.add(i,true);
mBooleanArrayList.remove(i+1);
mMyadapter.Refresh(mBooleanArrayList);
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("urlwebview", array.get(i).get("urlwebview"));
startActivity(intent);
}
});
}
private void Refreshtext() {
new Thread() {
@Override
public void run() {
try {
URL url = new URL("http://v.juhe.cn/toutiao/index?type=&key=2ca3a5b1cb6edf55250bff550ac34325");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
InputStream inputStream = urlConnection.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int lenth = -1;
while ((lenth = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, lenth);
byteArrayOutputStream.flush();
}
byteArrayOutputStream.close();
inputStream.close();
String s = byteArrayOutputStream.toString();
JSONObject jsonObject = new JSONObject(s);
int error_code = jsonObject.getInt("error_code");
if (error_code == 0) {
JSONObject result = jsonObject.getJSONObject("result");
JSONArray data1 = result.getJSONArray("data");
for (int i = 0; i < data1.length(); i++) {
JSONObject jsonObject1 = data1.getJSONObject(i);
String category = jsonObject1.getString("author_name");
String title = jsonObject1.getString("title");
String date = jsonObject1.getString("date");
String urlwebview = jsonObject1.getString("url");
String thumbnail_pic_s = jsonObject1.getString("thumbnail_pic_s");
HashMap<String, String> stringStringHashMap = new HashMap<>();
stringStringHashMap.put("category", category);
stringStringHashMap.put("title", title);
stringStringHashMap.put("date", date);
stringStringHashMap.put("urlwebview", urlwebview);
stringStringHashMap.put("thumbnail_pic_s", thumbnail_pic_s);
array.add(stringStringHashMap);//上面執(zhí)行刪除
handler.sendEmptyMessage(0x110);
}
} else {
handler.sendEmptyMessage(404);
}
} else {
handler.sendEmptyMessage(404);
}
} catch (Exception e) {
e.printStackTrace();
handler.sendEmptyMessage(404);
}
}
}.start();
}
}
activity_main.xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context="com.example.yanchenglong.MainActivity">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</ListView>
<Button
android:id="@+id/Refresh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="刷新數(shù)據(jù)"/>
</LinearLayout>
MyAdapter 適配器
package com.example.yanchenglong;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import static com.example.yanchenglong.R.id.textView4;
/**
* Created by Administrator on 2018/7/13 0013.
*/
public class Myadapter extends BaseAdapter implements AbsListView.OnScrollListener {
ArrayList<HashMap<String, String>> array;
Context context;
private ImageLoader mImageLoader;
private int mStart, mEnd;
private boolean mFirsrIn;
public static String[] URLS;//用來(lái)保存獲取當(dāng)前圖片的URL地址
ArrayList<Boolean> mBooleanArrayList;
public Myadapter(Context context, ArrayList<HashMap<String, String>> array, ListView listview, ArrayList<Boolean> mBooleanArrayList) {
this.context = context;
this.array = array;
this.mBooleanArrayList=mBooleanArrayList;
mImageLoader = new ImageLoader(listview);//對(duì)ListView操作
URLS = new String[array.size()];//空間大小
for (int i = 0; i < array.size(); i++) {
URLS[i] = array.get(i).get("thumbnail_pic_s");
}
listview.setOnScrollListener(this);
mFirsrIn = true;
}
@Override
public int getCount() {
return array.size();
}
@Override
public Object getItem(int i) {
return array.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
Dataf dataf = null;
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
dataf = new Dataf();
view = View.inflate(context, R.layout.item, null);
dataf.itemImage = view.findViewById(R.id.item_image);
dataf.textView2 = view.findViewById(R.id.textView2);
dataf.textView3 = view.findViewById(R.id.textView3);
dataf.textView4 = view.findViewById(textView4);
view.setTag(dataf);
} else {
dataf = (Dataf) view.getTag();
}
// new MyTask(dataf.itemImage).execute(array.get(i).get("thumbnail_pic_s"));
// DownImage downImage = new DownImage(array.get(i).get("thumbnail_pic_s"));
// downImage.loadImage(new DownImage.ImageCallBack() {
// @Override
// public void getDrawable(Drawable drawable) {
// dataf.itemImage.setImageDrawable(drawable);
// }
// });
String url = array.get(i).get("thumbnail_pic_s");
dataf.itemImage.setTag(url);//綁定對(duì)應(yīng)的圖片Url
//調(diào)用showimagebythread把圖片和圖片URL傳過(guò)去
// new ImageLoader().showimagebythread(dataf.itemImage,url);
mImageLoader.showImageByAsyncTask(dataf.itemImage, url);
dataf.textView2.setText(array.get(i).get("category"));
dataf.textView4.setText(array.get(i).get("title"));
mBooleanArrayList.add(false);//添加標(biāo)記
if(mBooleanArrayList.get(i)){
dataf.textView4.setTextColor(Color.parseColor("#999999"));
}
dataf.textView3.setText(array.get(i).get("date"));
return view;
}
@Override
public void onScrollStateChanged(AbsListView absListView, int i) {
if (i == SCROLL_STATE_IDLE) {//停止?fàn)顟B(tài)
//加載可見(jiàn)項(xiàng)
mImageLoader.loadImages(mStart, mEnd);
} else {
//停止加載
mImageLoader.cancelAllTasks();
}
}
public void Refresh(ArrayList<Boolean> mBooleanArrayList){
this.mBooleanArrayList=mBooleanArrayList;
notifyDataSetChanged();
}
@Override//參數(shù)二是第一個(gè)可見(jiàn)元素的位置,第三個(gè)是當(dāng)前可見(jiàn)元素的長(zhǎng)度
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int i2) {
mStart = firstVisibleItem;
mEnd = firstVisibleItem + visibleItemCount;
//第一次顯示時(shí)候調(diào)用
if (mFirsrIn && visibleItemCount > 0) {
mImageLoader.loadImages(mStart, mEnd);
mFirsrIn = false;
}
}
class Dataf {
private ImageView itemImage;//圖標(biāo)
private TextView textView2;//標(biāo)題
private TextView textView3;//時(shí)間
private TextView textView4;//內(nèi)容
}
class MyTask extends AsyncTask<String, Integer, Bitmap> {
ImageView ig;
MyTask(ImageView ig) {
this.ig = ig;
}
@Override
protected Bitmap doInBackground(String... strings) {
Log.d("data", strings[0]);
URL url = null;
try {
url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(10000);
con.setConnectTimeout(10000);
con.connect();
Log.d("data", con.getResponseCode() + "");
if (con.getResponseCode() == 200) {
InputStream is = con.getInputStream();
return BitmapFactory.decodeStream(is);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
ig.setImageBitmap(bitmap);
}
}
}
適配器內(nèi)容布局adapter,item
<?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="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/item_image"
android:layout_width="100dp"
android:layout_height="100dp"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="標(biāo)題"/>
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:text="是按"/>
<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="@id/textView2"
android:layout_centerVertical="true"
android:text="內(nèi)容"/>
</RelativeLayout>
</LinearLayout>
兩種方法可以
一 DownImage downImage = new DownImage(array.get(i).get("thumbnail_pic_s"));
DownImage類
package com.example.yanchenglong;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import java.net.URL;
/**
* Created by Administrator on 2018/7/13 0013.
*/
public class DownImage {
public String image_path;
public DownImage(String image_path) {
this.image_path = image_path;
}
public void loadImage(final ImageCallBack callBack) {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Drawable drawable = (Drawable) msg.obj;
callBack.getDrawable(drawable);
}
};
new Thread(new Runnable() {
@Override
public void run() {
try {
Drawable drawable = Drawable.createFromStream(new URL(
image_path).openStream(), "");
Message message = Message.obtain();
message.obj = drawable;
handler.sendMessage(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public interface ImageCallBack {
public void getDrawable(Drawable drawable);
}
}
二就是MyTask異步
new MyTask(dataf.itemImage).execute(array.get(i).get("thumbnail_pic_s"));
class MyTask extends AsyncTask<String,Integer,Bitmap> {
ImageView ig;
MyTask(ImageView ig){
this.ig = ig;
}
@Override
protected Bitmap doInBackground(String... strings) {
Log.d("data",strings[0]);
URL url = null;
try {
url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(10000);
con.setConnectTimeout(10000);
con.connect();
Log.d("data",con.getResponseCode()+"");
if(con.getResponseCode() == 200){
InputStream is = con.getInputStream();
return BitmapFactory.decodeStream(is);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
ig.setImageBitmap(bitmap);
}
}
三用緩存ImageLoader
package com.example.yanchenglong;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.LruCache;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
/**
* //異步加載圖片
* Created by Administrator on 2018/7/14 0014.
*/
public class ImageLoader {
public ImageView mImageView;
//緩存Lru算法
private LruCache<String, Bitmap> mCache;
private ListView mListView;
private HashSet<NewAsyncTask> mTask;
public ImageLoader(ListView listview) {
mListView = listview;
mTask = new HashSet<>();
//獲取最大可用內(nèi)存
int maxMemoy = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemoy / 4;
//初始化
mCache = new LruCache<String, Bitmap>(cacheSize) {
@Override//用于獲取存放每一個(gè)對(duì)象的大小//加載正確的內(nèi)存大小
protected int sizeOf(String key, Bitmap value) {
//將Bitmap實(shí)際大小緩存進(jìn)去
//在每次存入緩存的時(shí)候調(diào)用
return value.getByteCount();//返回對(duì)象的實(shí)際大小
}
};
}
//增加到緩存
public void addBitmapToCache(String url, Bitmap bitmap) {
if (getBitmapFromCache(url) == null) {
mCache.put(url, bitmap);
}
}
//從緩存中獲取數(shù)據(jù)
public Bitmap getBitmapFromCache(String url) {
return mCache.get(url);
}
// Handler hanler = new Handler() {
// @Override
// public void handleMessage(Message msg) {
// if (mImageView.getTag().equals(mUrl)) {
// mImageView.setImageBitmap((Bitmap) msg.obj);
// }
// }
// };
// public void showimagebythread(ImageView imageView, final String url) {
// mImageView = imageView;//item中的imageView付給了mImageView那么mImageView的更改就是把Item中修改
// mUrl = url;//使用成員變量,將對(duì)應(yīng)的數(shù)據(jù)進(jìn)行緩存從而避免網(wǎng)絡(luò)不穩(wěn)定導(dǎo)致一個(gè)時(shí)序上的混亂
// new Thread() {
// @Override
// public void run() {
// Bitmap bitmap = getBitmapFromURL(url);
// Message obtain = Message.obtain();
// obtain.obj = bitmap;
// hanler.sendMessage(obtain);
// }
// }.start();
//
// }
public Bitmap getBitmapFromURL(String urlstring) {
Bitmap bitmap;
InputStream is = null;
try {
URL url = new URL(urlstring);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
urlConnection.disconnect();//釋放鏈接資源
return bitmap;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
//用來(lái)加載從start到end的所有圖片
public void loadImages(int start, int end) {
for (int i = start; i < end; i++) {
if (Myadapter.URLS.length >=0) {
String url = Myadapter.URLS[i];
//從緩存中取出對(duì)應(yīng)的圖片
Bitmap bitmap = getBitmapFromCache(url);
//如果緩存中沒(méi)有,必須去網(wǎng)絡(luò)下載
if (bitmap == null) {
NewAsyncTask newAsyncTask = new NewAsyncTask(url);
newAsyncTask.execute(url);
mTask.add(newAsyncTask);
} else {
ImageView imageview = (ImageView) mListView.findViewWithTag(url);//找到指定Tag來(lái)訪問(wèn)他對(duì)應(yīng)的ImageView
imageview.setImageBitmap(bitmap);
}
}
}
}
public void cancelAllTasks() {
if (mTask != null) {
for (NewAsyncTask task : mTask) {
task.cancel(false);//true是強(qiáng)制停止,false是執(zhí)行完取消
}
}
}
public void showImageByAsyncTask(ImageView imageview, String Url) {
//從緩存中取出對(duì)應(yīng)的圖片
Bitmap bitmap = getBitmapFromCache(Url);
//如果緩存中沒(méi)有,必須去網(wǎng)絡(luò)下載
if (bitmap == null&&imageview.getTag().equals(Url)) {//我在滾動(dòng)停止時(shí)加載了
// imageview.setBackgroundResource(R.mipmap.ic_launcher);//正在下載
// 網(wǎng)絡(luò)下載
// new NewAsyncTask(Url).execute(Url);
} else {
imageview.setImageBitmap(bitmap);
}
}
private class NewAsyncTask extends AsyncTask<String, Void, Bitmap> {
// private ImageView mImageView;
private String mUrl;
//傳遞ImageView構(gòu)造ImageView imageview,
public NewAsyncTask(String url) {
// mImageView = imageview;
mUrl = url;
}
@Override
protected Bitmap doInBackground(String... strings) {
String url = strings[0];
//從網(wǎng)絡(luò)獲取圖片
Bitmap bitmapFromURL = getBitmapFromURL(strings[0]);
if (bitmapFromURL != null) {
//將不再緩存的圖片加入緩存
addBitmapToCache(url, bitmapFromURL);
}
return bitmapFromURL;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
// if (mImageView.getTag().equals(mUrl)) {
// mImageView.setImageBitmap(bitmap);
// }
ImageView imageview = mListView.findViewWithTag(mUrl);
if (imageview != null && bitmap != null&&imageview.getTag().equals(mUrl)) {
imageview.setImageBitmap(bitmap);
}
mTask.remove(this);
}
}
}
main2Activity
package com.example.yanchenglong;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Main2Activity extends AppCompatActivity {
private WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
webview = (WebView) findViewById(R.id.webview);
Intent intent = getIntent();
if(intent!=null){
String urlwebview = intent.getStringExtra("urlwebview");
webview.loadUrl(urlwebview);
webview.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
setTitle(url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
});
}}
}
main2Activity布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.yanchenglong.Main2Activity">
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</LinearLayout>
還可以去Github搜索smart image view看看