How to get a Drawable id by name

Asked

Viewed 200 times

0

I tried it like this but it’s 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 );
    }
  • What is the content of nome_foto?

  • the name of the photo in the drawable , type foto1

1 answer

2


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

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

imagem.setImageResource(drawableId );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.