如果我必须以编程方式在按钮上设置图像,那么我使用以下代码:
source
现在情况是我已经将数据库中的图像名称读入变量。因此,假设我的变量具有以下值:
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);
现在,当图像名称存储在变量中时,如何在按钮上设置相同的图像。
答案 0 :(得分:0)
使用以下方法从字符串中获取图像。
private int getImageFromString(String name) {
int resId = getResources().getIdentifier(name, "drawable", getPackageName());
return resId;
}
答案 1 :(得分:0)
您可以动态创建可绘制资源ID引用,如下所示
int resId=getResources().getIdentifier(img_str, "drawable", context.getPackageName())
img = ResourcesCompat.getDrawable(getResources(), resId, null )
当然,如果资源名称错误,请不要忘记尝试捕获
答案 2 :(得分:0)
你可以通过itss name,
获得如下的drawableResources resources = context.getResources();
final int resourceId = resources.getIdentifier(imgName, "drawable", context.getPackageName());
return resources.getDrawable(resourceId);
答案 3 :(得分:0)