首页 > 解决方案 > 在按钮名称来自数据库的按钮上设置图像

问题描述

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

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

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

标签: androidstringimage

解决方案


您可以按如下方式动态创建可绘制资源 id 引用

int resId=getResources().getIdentifier(img_str, "drawable", context.getPackageName())
img = ResourcesCompat.getDrawable(getResources(), resId, null )

当然不要忘记 try catch 以防资源名称错误


推荐阅读