android - 在按钮名称来自数据库的按钮上设置图像
问题描述
如果我必须以编程方式在按钮上设置图像,那么我使用以下代码:
Drawable img;
ToggleButton tb_button = (ToggleButton) findViewById(R.id.tglButton);
img = ResourcesCompat.getDrawable(getResources(), R.drawable.p189, null );
tb_button.setCompoundDrawables(img,null,null,null);
现在的情况是我已经将图像的名称从数据库读入了一个变量。因此,假设我的变量具有以下值:
String img_str= "p189";
现在,当图像名称存储在变量中时,如何在按钮上设置相同的图像。
解决方案
您可以按如下方式动态创建可绘制资源 id 引用
int resId=getResources().getIdentifier(img_str, "drawable", context.getPackageName())
img = ResourcesCompat.getDrawable(getResources(), resId, null )
当然不要忘记 try catch 以防资源名称错误
推荐阅读
- java - 如何维护 2 个不同的 Web 应用程序之间的用户会话?
- google-chrome - Chrome 扩展原生消息在 MacOS 上不起作用
- c# - 需要一种策略来缓存有关对象的信息而不使其保持活动状态
- android - Android:layout_weight 不适用于 Button 和 LinearLayout
- jenkins - 詹金斯构建触发器不等待孩子的孩子完成
- node.js - 在 Restify API 中实现的 Socket.io 的蝗虫负载测试导致显着减速
- ruby-on-rails - 找不到表(升级到较新的 Ruby 和 Rails 版本后)
- maven - 复制编译好的maven项目
- artifactory - 将作用域 npm 包发布到 Artifactory Online
- rest - REST calculateroute 想要提供到达时间来确定何时离开