Nikolay Morozov
Nikolay Morozov

Reputation: 33

Passing variable into findViewByID

I have the following setup. In my xml i have a bunch of image views. I am trying to show only one of them depending on the number set in preferences and the day of week. This must be really easy but i can't find out the correct way to pass variable into findViewByID. Here is code snippet:

String groupName = "R.id."+prefs.getString("groupListKey", "<unset>")+"_"+(Calendar.getInstance().get(Calendar.DAY_OF_WEEK));

ImageView image = (ImageView) findViewById(groupName);

Upvotes: 1

Views: 3012

Answers (2)

Chopin
Chopin

Reputation: 1452

findViewById receives an int as an argument, which is one of the generated in the R.id class.

You can have an array with your ids:

int[] imagesIds = new int[] { R.id.image1, ... R.id.image7 };

And then determine the index based on your conditions:

int imageIndex = ...
ImageView image = (ImageView) findViewById(imagesIds[imageIndex]);

Upvotes: 1

dymmeh
dymmeh

Reputation: 22306

findViewById() expects you to pass it an integer that represents a resource identifier. You are trying to pass it a string

Your best bet would be to have a conditional statement that evaluates your day of week and returns you the proper ID rather than doing it the way you are

 int resourceId = 0;
 switch (Calendar.getInstance().get(Calendar.DAY_OF_WEEK)) {
     case Calendar.SUNDAY:
         resourceId = R.id.sundayView;
         break;

     case Calendar.MONDAY:
         resourceId = R.id.mondayView;
         break;

     ...etc
 }

ImageView image = (ImageView) findViewById(resourceId);

Upvotes: 3

Related Questions