我正在开发Android应用程序。在我的应用程序中,我必须使用适配器。所以我使用了简单的适配器。
int[] flags = new int[]{
R.drawable.img1,
R.drawable.img2,
};
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<number.size();i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", number.get(i));
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
String[] from = { "flag","txt"};
// Ids of views in listview_layout
int[] send = { R.id.flag,R.id.txt};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.autocomplete_layout, from, send);
现在我想使用我自己的drawable arraylist而不是resourse。
Drawable d="some downloaded image from server"
现在我想在hashmap中使用上面的d。
hm.put("flag", d.toString() );
上面的stamenet无法正常工作。我知道它早先发送图片ID。现在我正在将图像转换为字符串。
所以我必须将我的图像放到hashmap hm。但是,如果我使用下载的可绘制图像,我该怎么办?
答案 0 :(得分:2)
//这可能有助于你
[1]首先你需要
HashMap<String, Object> hm= new HashMap<String, Object>();
Bitmap bmImg;
[2]对于在线图像,需要1个函数来获取Bitmap对象
public void downloadFile(final String fileUrl)
{
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
// imageLoadedHandler.sendEmptyMessage(FAILED);
} catch (IOException e) {
// imageLoadedHandler.sendEmptyMessage(FAILED);
}
}
//用于将在线图像放入带有线程的hasmap中并在此处填写数据
for(int i=0;i<number.size();i++){
HashMap<String, Object> hm= new HashMap<String, Object>();
new Thread() {
public void run()
{
downloadFile(smtLink[ii]);
hm.put("image", bmImg);
};
}.start();
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
//并且需要viewbinder类
class MyViewBinder implements ViewBinder
{
@Override
public boolean setViewValue(View view, Object data,String textRepresentation)
{
if((view instanceof ImageView) & (data instanceof Bitmap))
{
ImageView iv = (ImageView) view;
Bitmap bm = (Bitmap) data;
iv.setImageBitmap(bm);
return true;
}
return false;
}
}
//现在使用下面的简单适配器设置此数据,此处根据您的要求使用您的adpter进行更改
adapater1 = new SimpleAdapter(News.this, list, R.layout.homrow, new String[] { "im", "Titel", "Sourcetag", "Date1","im1" },
new int[] { R.id.homerowmain,R.id.homerowtitle, R.id.homerowsourcetag,R.id.homerowdate, R.id.homerowimgaerrow });
adapater1.setViewBinder(new MyViewBinder());
itemlist.setAdapter(adapater1);
答案 1 :(得分:0)
试试这个
Integer[] flags = {
R.drawable.Yourimg1, R.drawable.Yourimg2,
R.drawable.Yourimg3, R.drawable.Yourimg4,
};
答案 2 :(得分:0)
确保在导入中没有android.R ...并添加自己的R文件:)