[英]Custom ArrayAdapter Showing same image for each entry
顏色從列表中的所有項目更改為LAST項目,例如,如果最后一種顏色是黑色,則所有項目都具有黑色(而不是正確的顏色)
ListView lv = (ListView) convertView.findViewById(R.id.lv);
LogAdapter la = new LogAdapter(m_this,R.layout.logspinner,data);
lv.setAdapter(la);
請參閱下面的類-ICON是每個項目唯一的imageview
我傳遞了不同的十六進制值-當我逐步執行代碼時,正確使用了十六進制值
public class LogAdapter extends ArrayAdapter<HashMap<String, ?>> {
public LogAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public LogAdapter(Context context, int resource, ArrayList<HashMap<String, ?>> items) {
super(context, resource, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.logspinner, null);
}
HashMap<String, ?> p = getItem(position);
if (p != null) {
ImageView imageV = (ImageView) v.findViewById(R.id.imageView1);
if(imageV != null) {
Object o = p.get("Icon");
if (o != null) {
String colorhex = (String.valueOf(o));
Drawable myIcon = getContext().getResources().getDrawable(R.drawable.mark_ffffff);
myIcon.setColorFilter(colorhex, PorterDuff.Mode.MULTIPLY);
imageV.setImageDrawable(myIcon);
}
}
}
return v;
}}
嘗試進行的修改:
if(imageV != null) {
Object o = p.get("Icon");
if (o != null) {
String colorhex = (String.valueOf(o));
Drawable myIcon = getContext().getResources().getDrawable(R.drawable.mark_ffffff);
myIcon.setColorFilter(PColor(colorhex), PorterDuff.Mode.MULTIPLY);
Bitmap b = drawableToBitmap(myIcon);
imageV.setImageBitmap(b);
}
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap = null;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
添加mutate解決了該問題
Drawable myIcon = getContext().getResources().getDrawable(R.drawable.mark_ffffff);
myIcon = myIcon.mutate();
myIcon.setColorFilter(PColor(colorhex), PorterDuff.Mode.MULTIPLY);
來源: http : //android-developers.blogspot.com/2009/05/drawable-mutations.html
Context.getResources()中的資源僅預先實例化一次,以實現更好的重用和更少的內存壓力。 因此,從本質上講,您使用的是Drawable的相同實例,因此在這種情況下,僅最后一個濾色器適用。
此外,應使用Drawables在畫布上實際繪制一些東西。 您應該能夠1)使用新的Canvas(Bitmap )創建位圖和Canvas,2)將此Drawable繪制到該Canvas,以及3)將該Bitmap設置為ImageView。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.