0

I am making an Android app of Checkers based on XML widget (like imageview). I made a table of 8X8 of imageviews and call their id like so (i00 , i01 etc). I have two questions:

  1. I've tried to make a reference of the imageviews in the code like this:

    ImageView img = (ImageView) findViewById(R.id.i00);
    

    and it gives me an error:

    "i00 cannot be resolved or is not a field"
    
  2. Is there any way of getting id by a string? For example I have a imageview which id is i01, can I get it by:

    String str = "i01"
    

    and then give str as a parameter for some kind of method?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
nivik
  • 51
  • 1
  • 5

1 Answers1

0

1: That call is correct, check this thread which talks further about that error:
“id cannot be resolved or is not a field” error

2: Something like this should work:

String str = "i02";
int id = getResources().getIdentifier(str, "id", getPackageName());
ImageView img = (ImageView) findViewById(id);

Check this link for more information findViewById with String

Community
  • 1
  • 1
Razz
  • 220
  • 1
  • 6
  • Cool, could you clarify your second problem? I don't think I quite understood it. – Razz Dec 09 '14 at 19:17
  • my second quesion is if there is a way to call an id insted of findViewById , if i want to use a string that contain the name of the id. like String str ="i02" and then findViewById(R.id.str) – nivik Dec 09 '14 at 19:20
  • @nivik try that and see if it works. Also if this answer has been helpful, consider upvoting/accepting it as the answer. – Razz Dec 09 '14 at 19:29
  • what superclass do i need to use this getResources() method? – nivik Dec 13 '14 at 11:22
  • You would need a Context. – Razz Dec 15 '14 at 01:20