Si8
Si8

Reputation: 9225

Use index to assign drawable value

I have a bunch of ImageViews in my XML file

Their IDs are:

ivIcon0
ivIcon1
ivIcon2
ivIcon3

If I have an int k; value of 1 I want to only display ivIcon1 and if I have int k value of 0 I want to display 'ivIcon0`

I tried the following:

int iconResource = R.id.ivIcon(k);

Which gives me an error. I am sure it's simple but can't seem to figure it out. I want to set the background of the ID matching the iconResource to R.drawable.iconpressed

I have a widget which has the following line:

RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.widgetlayout);

And then I can use the following line to set the image source:

views.setImageViewResource("THE ID FROM THE INDEX", "THE DRAWABLE");

But the above two lines does not work in an Activity

Upvotes: 0

Views: 245

Answers (2)

Si8
Si8

Reputation: 9225

My solution that works in case others need it in the future:

if(Arrays.asList(myarraylist).contains(df.format(Calendar.getInstance(Locale.US).getTime()))) {
        int index = Arrays.asList(suspendedDates).indexOf(df.format(Calendar.getInstance(Locale.US).getTime()));

        int k = MainActivity.this.getResources().getIdentifier("ivIcon" + index, "id", MainActivity.this.getPackageName());

        ImageView view = (ImageView) findViewById(k);

        view.setImageResource(R.drawable.caliconpressed);
    }

Upvotes: 0

Simon Forsberg
Simon Forsberg

Reputation: 13351

Create an int array:

int[] resources = { R.id.ivIcon0, R.id.ivIcon1, R.id.ivIcon2, R.id.ivIcon3 };

And then access the id by using int iconResource = resources[k];

OR get the id from a String (if you're doing this in an activity, replace "context" with "this"

int iconResource = context.getResources().getIdentifier("ivIcon" + k, "id", context.getPackageName());

And then to get the view you do: ImageView view = (ImageView) findViewById(iconResource)

Personally, I prefer to use the int-array approach as long as the number of possible id's isn't too big. When using the get-id-from-String approach you will end up with the id 0 if it was not found, while the values in the int-array will produce a compiler error if they are not found.

Upvotes: 1

Related Questions