关闭

Android - 异步下载图片的简单实现

标签: androidlistview布局xml
508人阅读 评论(0) 收藏 举报
分类:
public class MainActivity extends Activity {
private TextView result;
private ItemAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 创建请求队列
// volley可以下载网页、图片、json
final RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
result = (TextView) findViewById(R.id.downloadresult);

// 创建请求
String url = "http://192.168.48.104/h.txt";
// 参数 1——url 2——下载成功相应 3——下载失败响应
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
// 下载完成,回调
@Override
public void onResponse(String response) {
// TODO Auto-generated method stub
System.out.println("=================" + response);
result.setText(response);
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
System.out.println("=================下载失败");
result.setText("网页下载失败");
}
});
// 添加请求到请求队列
// queue.add(stringRequest);

// 二、下载图片
// 参数 1——图片URL 2——下载成功响应 3——图片宽度 4——图片高度(0为原高)5——下载失败响应
String imagUrl = "http://b.hiphotos.baidu.com/image/pic/item/b219ebc4b74543a9030fb57e1d178a82b901146f.jpg";
ImageRequest imageRequest = new ImageRequest(imagUrl,
new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap response) {
// TODO Auto-generated method stub
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(response);
result.setText("图片下载成功!");
}
}, 0, 0, Config.ARGB_8888, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
result.setText("图片下载失败!");
}
});
// queue.add(imageRequest);
// 下载json
// String jsonUrl = "http://bcs.duapp.com/openclass/images%2Fdata.json";
String jsonUrl = "http://121.42.13.103/cyberHotel/1.txt";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(jsonUrl,
new Response.Listener<JSONArray>() {
private String name;
private String image;

@Override
public void onResponse(JSONArray response) {
// TODO Auto-generated method stub
// 解析Json
ArrayList<ItemData> data = new ArrayList<ItemData>();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObject = response
.getJSONObject(i);
name = jsonObject.getString("name");
image = jsonObject.getString("image");
// 封装name image
ItemData item = new ItemData(name, image);
data.add(item);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ListView list = (ListView) findViewById(R.id.list);
result.setText("Json解析成功");
adapter = new ItemAdapter(MainActivity.this, data,queue);
list.setAdapter(adapter);
}
}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsonArrayRequest);
}
}

public class ItemAdapter extends BaseAdapter {
Context context;
ArrayList<ItemData> data;
LayoutInflater inflater;
private ImageLoader imageLoader;


public ItemAdapter(Context context, ArrayList<ItemData> data,RequestQueue queue) {
super();
this.context = context;
this.data = data;
inflater = inflater.from(context);
imageLoader=new ImageLoader(queue, new ImageCache() {

//存图片
@Override
public void putBitmap(String url, Bitmap bitmap) {
// TODO Auto-generated method stub
File cacheDir = ItemAdapter.this.context.getExternalCacheDir();
String fileName=getFileName(url);
//缓存文件
File file = new File(cacheDir,fileName);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getFileName(String url){
String[] split = url.split("/");
return split[split.length-1];

}

//取图片
@Override
public Bitmap getBitmap(String url) {
// TODO Auto-generated method stub
File cacheDir = ItemAdapter.this.context.getExternalCacheDir();
String fileName = getFileName(url);
File file = new File(cacheDir,fileName);
//判断文件是否存在
if(file.exists()){
return BitmapFactory.decodeFile(file.getPath());
}
return null;

}
});
}


@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}


@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}


@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}


@Override
public View getView(int position, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LinearLayout layout = (LinearLayout) inflater.inflate(
R.layout.listitem, null);
TextView name = (TextView) layout.findViewById(R.id.item_text);
NetworkImageView image = (NetworkImageView) layout.findViewById(R.id.item_image);
name.setText(data.get(position).getName().toString());

System.out.println("======================"+position);
image.setDefaultImageResId(R.drawable.ic_launcher);
//设置图片
image.setImageUrl(data.get(position).getImage(), imageLoader);
return layout;
}
}



public class ItemData {

public ItemData() {
super();
}
public ItemData(String name, String image) {
super();
this.name = name;
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
private String name;
private String image;
}



activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    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=".MainActivity" >
    <TextView
        android:id="@+id/downloadresult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <ImageView
        android:id="@+id/img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
<ListView 
   android:id="@+id/list"
   android:layout_width="match_parent"
android:layout_height="match_parent"
   ></ListView>
</LinearLayout>


listitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <com.android.volley.toolbox.NetworkImageView 
        android:id="@+id/item_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_launcher"
        />
    <TextView 
        android:id="@+id/item_text"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="center_vertical"
        android:layout_marginLeft="20dp"
        />
</LinearLayout>


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:24991次
    • 积分:638
    • 等级:
    • 排名:千里之外
    • 原创:45篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条