Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

java - How to dynamically reference resources in the R.drawable folder in Android?

I have the following code for my Adapter:

@Override
public void onBindViewHolder(GameViewHolder holder, int position) {
    final Games game = gameList.get(position);
    holder.awayTeamImageView.setBackgroundResource(R.drawable.fortyers);
}

The above works perfectly but I am hard coding the image that will be displayed. What I really need is to get the background image from the game list and I am looking to do something like this:

 holder.awayTeamImageView.setBackgroundResource(R.drawable.game.getaBackground());

But that causes an error

How can I dynamically set the imageView's background resource?

UPDATE:

I have attached a screenshot of the desired effect.

Each week the schedule will change so the list will always be different depending on the week selected.

enter image description here

Game constructor:

public Games(DataSnapshot game) {

    this.AwayTeam = game.child("AwayTeam").getValue().toString();
    this.AwayId = Integer.parseInt(game.child("AwayId").getValue().toString());

    this.HomeTeam = game.child("HomeTeam").getValue().toString();
    this.HomeId = Integer.parseInt(game.child("HomeId").getValue().toString());

    this.aBackground = game.child("aBackground").getValue().toString();
    this.hBackground = game.child("hBackground").getValue().toString();

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create a list of String that will contain the id of your drawables, keep them in the order synced with the position and then get the id as per the position from the list to pass while setting the drawable.

If it's something reused in multiple places and the order is consistent, you can also go for an Enum to get the drawable id in terms of a certain key of your choice. You might need to figure the key using a when condition as per position if it's really dependant on the position.

Hope that works!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...