java - 如何在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();
}
解决方案
另一种可能对您有所帮助的方法是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);
推荐阅读
- ffmpeg - 连接 2 个文件后音频不同步
- vb.net - 如何阻止我的应用程序中的对象被处置?
- ansible - 使用 Ansible 复制模块进行远程到远程文件传输(同一远程主机)
- php - 如何在 octobrcms 中显示用户的所有帖子
- jquery - Django ajax 更新模型
- c# - 如何将 RestSharp 响应添加到 API 控制器?
- ansible - 如何对用户/组存在进行 Ansible 条件测试?
- reactjs - 大型模块化 React+Redux 应用程序中捆绑包之间松散耦合的策略是什么
- c++ - 使用文件描述符移动对象
- java - 不兼容的类型 - 泛型接口和实现