android-smart-image-view圖片載入簡單使用

我叫阿狸貓發表於2014-03-26

這個工具類是帶快取功能的圖片載入工具類,它自己會在新執行緒中進行操作。

下載地址:工具類下載地址

1.首先將工具類的com資料夾拷貝到工程中。

2.圖片元件不再用ImageView,而是使用com.loopj.android.image.SmartImageView

3.呼叫contentIV.setImageUrl("","","")進行載入圖片     也可以不設定後面的兩個引數

    第一個引數:圖片的Url

    第二個引數:圖片地址錯誤時候顯示的圖片

    第三個引數:圖片正在載入的時候顯示的圖片  

4.如果使用自定義載入圖片工具類的話,記得配置外儲存裝置的寫許可權,因為快取的時候會是將圖片快取到SD卡上了。如果使用SmartImageView就不需要配置了,因為它快取到了當前應用包下。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


import com.loopj.android.image.SmartImageView;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	private EditText pathET;
//	private ImageView contentIV;
	private NetService service;
	private Handler handler = new Handler();
	private SmartImageView contentIV;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		service = new NetService();
		pathET = (EditText) findViewById(R.id.pathET);
		contentIV = (SmartImageView) findViewById(R.id.contentIV);
	}
	
	public void go(View view){
		/*
		 * 第一個引數:圖片的Url
		 * 第二個引數:圖片地址錯誤時候顯示的圖片
		 * 第三個引數:圖片正在載入的時候顯示的圖片  
		 */
		contentIV.setImageUrl(pathET.getText().toString(),android.R.drawable.ic_delete,android.R.drawable.ic_popup_sync);
		//註釋是使用自定義載入圖片的工具類,如果使用SmartImageView  上面一句話即可。
		/*new Thread(){
			public void run() {
				try {
					String path = pathET.getText().toString();
					final Bitmap bitmap = service.getImage(path);
					handler.post(new Runnable() {
						@Override
						public void run() {
							contentIV.setImageBitmap(bitmap);
						}
					});
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "伺服器忙!", Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			};
		}.start();*/
	}
}



使用工具類載入圖片這個類就不需要寫了,這個類是自定義載入圖片的工具類
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * 自定義快取並顯示圖片的類
 * @author Administrator
 *
 */
public class NetService {

	public Bitmap getImage(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		File file = new File("/mnt/sdcard/"+URLEncoder.encode(path,"UTF-8"));
		if(file.exists()){//如果該檔案存在,則在訊息頭上加上此檔案最後修改日期,讓它和伺服器上的檔案的最後修改日期進行對比,如果不一樣則要進行載入,如果一樣則使用快取
			conn.setIfModifiedSince(file.lastModified());
		}
		
		int code = conn.getResponseCode();
		if(code==200){
			InputStream is = conn.getInputStream();
			int len = 0;
			byte[] buff = new byte[1024];
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			while((len=is.read(buff))!=-1){
				bos.write(buff, 0, buff.length);
			}
			Bitmap bitmap = BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.toByteArray().length);
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(bos.toByteArray());
			fos.close();
			bos.close();
			is.close();
			return bitmap;
		}else if(code==304){//如果最後修改日期一樣,則使用本地快取檔案
			return BitmapFactory.decodeFile(file.getAbsolutePath());
		}
		throw new RuntimeException("返回圖片異常");
	}
}


佈局

<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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.xxc.nettext.MainActivity$PlaceholderFragment" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/pathET"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="textUri" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="go"
            android:text="GO" />
    </LinearLayout>

    <com.loopj.android.image.SmartImageView
        android:id="@+id/contentIV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>



相關文章