0

I'm coding a trivia app for android and it consists of questions and image options. Each question has 2 image options which are android buttons with different backgrounds set to them.

There are only two OnClickListeners, and I am currently changing the background like this:

button1.setBackground(R.drawable.image1)

I have over 30 different images I will be using as backgrounds for the buttons, and it seems inefficient to call the code above with the name of the image (image1.png in example) hardcoded.

I'd like to make it all work off a very effective function, like this:

nextQuestion(Question q)
{
display.setText("" + q.getQ()) ; // setting a new question to TextView called display
button1.setBackground(R.drawable.(q.getRandom())) ; //change background off of variable
button1.setBackground(R.drawable.(q.correctAnswerIndex)) ; // one is correct, one random
}

But I couldn't find a way to use variables with setBackground() Is there any way I could do something like I wrote above? Thanks in advance!

4

1 回答 1

1
int resID = getResources().getIdentifier(icon, "drawable",  getPackageName()); 
iV.setImageResource(resID); 

将 resID 设置为您的 'q' 值并根据需要使用!

'icon' 是可绘制对象的名称

于 2013-11-10T21:00:04.090 回答