How to get a Drawable id by name

0

I tried this way more is returning 0

try {
        String nome_foto = itens.get(position).nome_foto;
        int drawableId = context.getResources().getIdentifier(nome_foto, "drawable", context.getPackageName());
        Log.e("",""+drawableId+" "+R.drawable.bertioga1+" "+nome_foto);
        imagem.setImageResource(drawableId );
    }
    
asked by anonymous 05.02.2015 / 21:18

1 answer

2

If you are already in the main context you do not need "context". See too if you are taking the name of the photo correctly. I tested it this way and it worked perfectly:

String nomeFoto = "nome_da_foto"; //sem o PGN, JPG, etc...
int drawableId = getResources().getIdentifier(nomeFoto, "drawable", getPackageName());

imagem.setImageResource(drawableId );
    
10.02.2015 / 01:01