2012-03-04 15 views
6

में नाम से संसाधन छवि प्राप्त करें मेरे पास एक कस्टम कर्सर एडाप्टर है और मैं एक सूची दृश्य में एक छवि दृश्य में एक छवि डालना चाहता हूं।कस्टम कर्सर एडाप्टर

मेरे कोड है:

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); 
    } 
} 

यह सब ठीक है, लेकिन मैं डेटाबेस (कर्सर) से छवि का नाम प्राप्त करना चाहते हैं। मैं

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

साथ करने की कोशिश की लेकिन वापसी त्रुटि:

+0

यदि आप कर्सर से प्राप्त करना चाहते हैं तो आप इसके बजाय 'कर्सर.getString' क्यों नहीं कहते हैं। और आपकी छवि कहां संग्रहीत है? –

उत्तर

13

आप केवल एक संदर्भ वस्तु पर एक getResources() कॉल कर सकते हैं "विधि getResources() प्रकार CustomImageListAdapter के लिए अपरिभाषित है"। चूंकि CursorAdapter का कन्स्ट्रक्टर ऐसा संदर्भ लेता है, बस एक वर्ग सदस्य बनाएं जो इसका ट्रैक रखता है ताकि आप इसका उपयोग (अनुमानतः) bindView(...) में कर सकें। आपको शायद getPackageName() के लिए भी इसकी आवश्यकता होगी।

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 आपने मुझे इसे हराया। :) – Squonk

+0

"एमएच" के लिए धन्यवाद। समाधान के लिए। ("MisterSquonk" के लिए भी) – Cuarcuiu

+0

आप गतिविधि के अंदर संदर्भ को जोड़ने के बिना getResources() का उपयोग क्यों कर सकते हैं? धन्यवाद। – Ricardo

संबंधित मुद्दे