Android ListView添加Bitmap

在自定义的simpleAdapter中,显示的图片资源都是程序内的本地资源,而且是以资源的ID(Resources)形式来表现的,有时候需要添加Bitmap。要想让ListView能显示Bitmap这是关键的代码。

simpleAdapter.setViewBinder(new ViewBinder() {
       	 
            @Override
            public boolean setViewValue(View view, Object data,
                    String textRepresentation) {
            	if(view instanceof ImageView && data instanceof Bitmap){  
                    ImageView i = (ImageView)view;  
                    i.setImageBitmap((Bitmap) data);  
                    return true;  
                }  
                return false;
            }
        });

下面的一个demo是下载一张图片,并且显示在ListView中。

itemlist.xml

<?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="match_parent"
    android:orientation="vertical" >
    
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        
        <TextView 
            android:id="@+id/TITLE_ID"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="20dp"
            android:text="这是标题"/>
       
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        
        <TextView 
            android:id="@+id/CONTENT_ID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingTop="20dp"
            android:text="这是内容"/>
        
        <ImageView 
            android:id="@+id/IMAG_ID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher"
            android:layout_marginLeft="220dp"
            android:layout_toRightOf="@id/CONTENT_ID"/>
        
    </RelativeLayout>
    
    
</LinearLayout>

mainActivity.xml

<RelativeLayout 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: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=".NewsActivity" >


    <ListView 
        android:id="@+id/LISTVIEW_ID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <ImageView 
        android:id="@+id/IMAGE_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

Activity.java里面有些是测试的代码,看下面的关键代码即可

package com.example.baidunews;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.StringBuilderPrinter;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;

public class NewsActivity extends Activity {

	private String Url = "https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png" ;
	private ListView listView ;
	private ArrayList<	HashMap<String, Object> >itemData = new ArrayList<HashMap<String,Object>>() ;
	private Bitmap bitMap  ;
	public StringBuilder str = new StringBuilder();
	public String s  ;
	private ImageView imageView ;
	private Util myUtil = new Util();
	private Handler handler ;
	private SimpleAdapter simpleAdapter ;
	private MyAsyncTask myAsyncTask = new MyAsyncTask() ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        
        handler = new Handler(){      	
        	@Override
        	public void handleMessage(Message msg){
        		str.append("as") ;
        		simpleAdapter.notifyDataSetChanged() ;      		
        	}
        } ;
        
        imageView = (ImageView) findViewById(R.id.IMAGE_ID) ;
        listView = (ListView) findViewById(R.id.LISTVIEW_ID) ;    
        simpleAdapter = new SimpleAdapter(this,itemData,R.layout.itemlist,
        		new String[]{"title","content","image"} ,new int[]{R.id.TITLE_ID,R.id.CONTENT_ID,R.id.IMAG_ID}) ;
        simpleAdapter.setViewBinder(new ViewBinder() {
       	 
            @Override
            public boolean setViewValue(View view, Object data,
                    String textRepresentation) {
            	if(view instanceof ImageView && data instanceof Bitmap){  
                    ImageView i = (ImageView)view;  
                    i.setImageBitmap((Bitmap) data);  
                    return true;  
                }  
                return false;
            }
        });
        
        
        myAsyncTask.execute(Url) ;  
       // dosome() ;
        //getData() ;
        listView.setAdapter(simpleAdapter) ;
       // imageView.setImageBitmap(bitMap) ;
        
    }

    
    public void dosome(){
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
    	            // 使用HttpURLConnection打开连接
    	            HttpClient httpClient = new DefaultHttpClient() ;
    	            HttpGet httpGet = new HttpGet("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png") ;
    	            HttpResponse httpResponse = httpClient.execute(httpGet) ;
    	            HttpEntity entity = httpResponse.getEntity() ;
    	            // 将得到的数据转化成InputStream
    	            InputStream is = entity.getContent();
    	            // 将InputStream转换成Bitmap
    	            bitMap = BitmapFactory.decodeStream(is);
    	            is.close();
    	            int i = 0;  
    	        } catch (MalformedURLException e) {
    	            // TODO Auto-generated catch block
    	            System.out.println("[getNetWorkBitmap->]MalformedURLException");
    	            e.printStackTrace();
    	        } catch (IOException e) {
    	            System.out.println("[getNetWorkBitmap->]IOException");
    	            e.printStackTrace();
    	        }
				handler.sendEmptyMessage(0) ;
			}
			
		}).start() ;
    	
    }
    

    public void getData(){
    	HashMap<String, Object> elem = new HashMap<String, Object>() ;
    	elem.put("title", str) ;
    	elem.put("content","内容1") ;
    	elem.put("image",bitMap);
    	itemData.add(elem) ;
    }
    
    
    public class MyAsyncTask extends AsyncTask<String, Integer , String>{
    
    	@Override
    	public String doInBackground(String...params){
    		
    		 try {
    	            // 使用HttpURLConnection打开连接
    	            HttpClient httpClient = new DefaultHttpClient() ;
    	            HttpGet httpGet = new HttpGet("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png") ;
    	            HttpResponse httpResponse = httpClient.execute(httpGet) ;
    	            HttpEntity entity = httpResponse.getEntity() ;
    	            // 将得到的数据转化成InputStream
    	            InputStream is = entity.getContent();
    	            // 将InputStream转换成Bitmap
    	            bitMap = BitmapFactory.decodeStream(is);
    	            is.close();
    	            int i = 0;  
    	        } catch (MalformedURLException e) {
    	            // TODO Auto-generated catch block
    	            System.out.println("[getNetWorkBitmap->]MalformedURLException");
    	            e.printStackTrace();
    	        } catch (IOException e) {
    	            System.out.println("[getNetWorkBitmap->]IOException");
    	            e.printStackTrace();
    	        }
    		 
    		return "" ;
    	}

		@Override
    	public void onPostExecute(String str1){
			HashMap<String, Object> elem = new HashMap<String, Object>() ;
	    	elem.put("title", "标题1") ;
	    	elem.put("content","内容1") ;
	    	elem.put("image", bitMap);
	    	itemData.add(elem) ;
	    	listView.setAdapter(simpleAdapter) ;
	    	//simpleAdapter.notifyDataSetChanged() ;
    		//imageView.setImageBitmap(bitMap) ;
	        
    	}	 
    } 
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.news, menu);
        return true;
    }
    
}




关键代码,下载图片

 public class MyAsyncTask extends AsyncTask<String, Integer , String>{
    
    	@Override
    	public String doInBackground(String...params){
    		
    		 try {
    	            // 使用HttpURLConnection打开连接
    	            HttpClient httpClient = new DefaultHttpClient() ;
    	            HttpGet httpGet = new HttpGet("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png") ;
    	            HttpResponse httpResponse = httpClient.execute(httpGet) ;
    	            HttpEntity entity = httpResponse.getEntity() ;
    	            // 将得到的数据转化成InputStream
    	            InputStream is = entity.getContent();
    	            // 将InputStream转换成Bitmap
    	            bitMap = BitmapFactory.decodeStream(is);
    	            is.close();
    	            int i = 0;  
    	        } catch (MalformedURLException e) {
    	            // TODO Auto-generated catch block
    	            System.out.println("[getNetWorkBitmap->]MalformedURLException");
    	            e.printStackTrace();
    	        } catch (IOException e) {
    	            System.out.println("[getNetWorkBitmap->]IOException");
    	            e.printStackTrace();
    	        }
    		 
    		return "" ;
    	}

		@Override
    	public void onPostExecute(String str1){
			HashMap<String, Object> elem = new HashMap<String, Object>() ;
	    	elem.put("title", "标题1") ;
	    	elem.put("content","内容1") ;
	    	elem.put("image", bitMap);
	    	itemData.add(elem) ;
	    	listView.setAdapter(simpleAdapter) ;
	    	//simpleAdapter.notifyDataSetChanged() ;
    		//imageView.setImageBitmap(bitMap) ;
	        
    	}	 
    } 

关键代码,SimpleAdapter的创建

 simpleAdapter = new SimpleAdapter(this,itemData,R.layout.itemlist,
        		new String[]{"title","content","image"} ,new int[]{R.id.TITLE_ID,R.id.CONTENT_ID,R.id.IMAG_ID}) ;
        simpleAdapter.setViewBinder(new ViewBinder() {
       	 
            @Override
            public boolean setViewValue(View view, Object data,
                    String textRepresentation) {
            	if(view instanceof ImageView && data instanceof Bitmap){  
                    ImageView i = (ImageView)view;  
                    i.setImageBitmap((Bitmap) data);  
                    return true;  
                }  
                return false;
            }
        });


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值