SimpleAdapter中使用Drawable和Bitmap對象的方法

SimpleAdapter中使用Drawable和Bitmap對象的方法

我們平常使用SimpleAdapter作爲ListView或GridView適配器時,如果要顯示圖片,我們通常使用圖片的id即R.drawable.xxx的方式來將圖片綁定到視圖上。

但是,如果我們要使用的圖片是個Drawable或Bitmap對象時,上面的方式就不能解決問題了。下面就介紹如何在SimpleAdapter中使用Drawable或Bitmap對象。


1.使用Drawable對象作爲SimpleAdapter要適配的圖片資源

SimpleAdapter adapter=new SimpleAdapter(this, items, R.layout.line, new String[]{"imgIco","appName","packageName"},new int[]{R.id.imgIco,R.id.tvAppName,R.id.tvAppDesc});

list.setAdapter(adapter);

//ViewBinder該類可以幫助SimpleAdapter加載圖片(如:Bitmap,Drawable)

adapter.setViewBinder(new ViewBinder() {

@Override

public booleansetViewValue(View view, Object data,

String textRepresentation) {

// TODO Auto-generated method stub

if(view instanceof ImageView && data instanceof Drawable){

ImageView iv = (ImageView)view;

iv.setImageDrawable((Drawable)data);

return true;

}else{

return false;

}

}

});


2.使用Bitmap對象作爲SimpleAdapter要適配的圖片資源


SimpleAdapter adapter=new SimpleAdapter(this, items, R.layout.line, new String[]{"imgIco","appName","packageName"},new int[]{R.id.imgIco,R.id.tvAppName,R.id.tvAppDesc});

list.setAdapter(adapter);

//ViewBinder該類可以幫助SimpleAdapter加載圖片(如:Bitmap,Drawable)

adapter.setViewBinder(new ViewBinder() {

@Override

public booleansetViewValue(View view, Object data,

String textRepresentation) {

// TODO Auto-generated method stub

if(view instanceof ImageView && data instanceof Bitmap){

ImageView iv = (ImageView)view;

iv.setImageBitmap((Bitmap) data);

return true;

}else{

return false; }

}

});


上面的方法其大致其流程是:首先檢查SimpleAdapter有沒有指定SimpleAdapter.ViewBinder,如果指定了就調用其setViewValue方法。

SimpleAdapter.ViewBinder是一個接口,也只有這一個方法,如果ViewBinder返回true表示我們已經完成了對這個View的數據綁定,就不再調用系統默認的實現,當然我們也可以設置一個ViewBinder添加一些功能後通過返回false再讓系統綁定數據,比如對按鈕添加響應事件,而按鈕上的文字由默認實現綁定。






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章