سؤال

I am wondering how i can set a Bitmap drawable resource from a dynamic variable that is the image name/ type string:

public CustomIcon getView(int position, View convertView, ViewGroup parent) {
        String label;
        String image;
        DataBaseManager db = new DataBaseManager(context);
        label = db.getIconLabel(mIcons.get(position));
        image = db.getIconImage(mIcons.get(position));
        Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(),
                parent.getResources().getIdentifier(image, "drawable", getApplicationContext().getPackageName()));
        Log.v(TAG, "current pos:"+ position);
        CustomIcon icon = new CustomIcon(context, bitmap,label);

        return icon;
    }

the part in question is

Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(),
                         R.drawable.[image]);

CODE CHANGED ABOVE -

هل كانت مفيدة؟

المحلول

The way to deal with this is to get the resource ID first and then use the BitmapFactory method:

String imgName = "myicon";
int resID = parent.getResources().getIdentifier(imgName, "drawable", "my.app.package.name");
Bitmap bitmap = BitmapFactory.decodeResource(parent.getResources(), resID);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top