在按钮名称来自数据库的按钮上设置图像

时间:2018-05-18 10:37:21

标签: android string image

如果我必须以编程方式在按钮上设置图像,那么我使用以下代码:

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

现在,当图像名称存储在变量中时,如何在按钮上设置相同的图像。

4 个答案:

答案 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,

获得如下的drawable
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(imgName, "drawable", context.getPackageName());
return resources.getDrawable(resourceId);

答案 3 :(得分:0)

详细说明ABK所说的内容。您可以获取Drawable ResId然后使用它来获取这样的函数中的drawable:

private Drawable getDrawableFromString(String name) {
    int resId = getResources().getIdentifier(name, "drawable", getPackageName());
    return getResources().getDrawable(resourceId);
}