首页 > 解决方案 > 如何在Android中动态引用R.drawable文件夹中的资源?

问题描述

我的适配器有以下代码:

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

以上工作完美,但我正在硬编码将显示的图像。我真正需要的是从游戏列表中获取背景图像,我正在寻找这样的事情:

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

但这会导致错误

如何动态设置 imageView 的背景资源?

更新:

我附上了所需效果的屏幕截图。

每周日程都会发生变化,因此列表将始终根据所选周而有所不同。

在此处输入图像描述

游戏构造函数:

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();

}

标签: javaandroidandroid-studio

解决方案


另一种可能对您有所帮助的方法是getIdentifier从字符串中使用。为此,您将背景字符串名称与资源中的名称相同。例如,如果您想显示,ic_menu_camera那么您aBackground应该是相同的字符串。

示例游戏类:

public class Game {

    String aBackground;

    public Game(String aBackground) {
        this.aBackground = aBackground;
    }

    public String getaBackground() {
        return aBackground;
    }

    public void setaBackground(String aBackground) {
        this.aBackground = aBackground;
    }
}

然后像这样使用它。阅读内联注释以详细了解。

//set the background name that you want same as name in your drawable folder
        // without any extension .png or .xml. Just name should be there
        Game game = new Game("ic_menu_camera");
        ImageView imageView = findViewById(R.id.imageView);
        //get the id by name using this
        /*  @param name The name of the desired resource.
             * @param defType Optional default resource type to find, if "type/" is
             *                not included in the name.  Can be null to require an
             *                explicit type.
             * @param defPackage Optional default package to find, if "package:" is
             *                   not included in the name.  Can be null to require an
             *                   explicit package.
             * 
             * @return int The associated resource identifier.  Returns 0 if no such
             *         resource was found.  (0 is not a valid resource ID.)
             * */
        int resId = getResources().getIdentifier(game.getaBackground(), "drawable",getPackageName());
        // then set that id to your image
        imageView.setBackgroundResource(resId);

推荐阅读