2012-03-04 18 views
6

Özel bir imleç bağdaştırıcısına sahibim ve bir görüntüyü bir ListView'de bir ImageView içine koymak istiyorum.Kaynak görüntüyü özel imleç bağdaştırıcısına getirme

Benim kodudur:

public class CustomImageListAdapter extends CursorAdapter { 

    private LayoutInflater inflater; 

    public CustomImageListAdapter(Context context, Cursor cursor) { 
    super(context, cursor); 
    inflater = LayoutInflater.from(context); 
    } 

    @Override 
    public void bindView(View view, Context context, Cursor cursor) { 
    // get the ImageView Resource 
    ImageView fieldImage = (ImageView) view.findViewById(R.id.fieldImage); 
    // set the image for the ImageView 
    flagImage.setImageResource(R.drawable.imageName); 
    } 

    @Override 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
    return inflater.inflate(R.layout.row_images, parent, false); 
    } 
} 

Bunların hepsi tamam ama veritabanı (imleç) den resmin adını almak istiyorum. Ben

String mDrawableName = "myImageName"; 
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 

ile çalıştı Ama hata döndürür:

+0

İmleç'ten almak istiyorsanız, neden bunun yerine 'cursor.getString' çağırmıyorsunuz? Ve senin görüntün nerede saklanıyor? –

cevap

13

Yalnızca Bağlam nesne üzerinde bir getResources() çağrıyı yapabilir "yöntemi GetResources() tipi CustomImageListAdapter için tanımlanmamış". CursorAdapter 'un yapıcısı böyle bir başvuru aldığından, (muhtemelen) bindView(...) içinde kullanabilmeniz için onu izleyen bir sınıf üyesi oluşturmanız yeterlidir. Muhtemelen getPackageName() için buna ihtiyacınız olacak.

private Context mContext; 

public CustomImageListAdapter(Context context, Cursor cursor) { 
    super(context, cursor); 
    inflater = LayoutInflater.from(context); 
    mContext = context; 
} 

// Other code ... 

// Now call getResources() on the Context reference (and getPackageName()) 
String mDrawableName = "myImageName"; 
int resID = mContext.getResources().getIdentifier(mDrawableName , "drawable", mContext.getPackageName()); 
+0

+1 bana onu dövdün. :) – Squonk

+0

"MH" ye teşekkürler. çözüm için. (ayrıca "MisterSquonk" için) – Cuarcuiu

+0

Neden içeriğin bir Etkinliğin içine eklenmeden getResources() yöntemini kullanabilirsiniz? Teşekkürler. – Ricardo

İlgili konular