【问题标题】:Obtaining Drawable object from string in Android Studio在 Android Studio 中从字符串中获取 Drawable 对象
【发布时间】:2016-02-13 08:06:15
【问题描述】:

我正在尝试找到一种通过字符串设置图像视图的方法。似乎 getResources() 已被弃用,我似乎找不到一种快速的方法来传递字符串并将图像加载到我的 imageView 中。我没有任何工作或有用的代码要呈现,我只是要求研究方法。 谢谢!

【问题讨论】:

  • 对不起,这个问题对我来说毫无意义。你能指出我不推荐使用哪个 getResources 的文档吗?您打算如何将字符串转换为图像?
  • 这里是一个例子:stackoverflow.com/questions/5254100/…我有我想访问的图像的名字,所以我希望通过他们的名字从drawable中访问它们。
  • 我在文档中看不到任何关于 getResources() 被弃用的信息:developer.android.com/reference/android/content/…
  • getDrawable(int id) 自 API 22 起已弃用(已被 getDrawable(int id, Theme theme) 取代),但 getResources() 并未弃用。

标签: android image android-studio


【解决方案1】:

theMatus 的答案是正确的。可通过int 标识符访问可绘制对象(即R.drawable.some_image 将具有相应的int 值)。要将String 转换为这样的值,您可以使用Resources.getIdentifier()

String mDrawableName = "some_image";
int resId = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());

要访问Drawable,您可以使用getResources().getDrawable(resId)。顺便说一句,getResources() 并没有被弃用,尽管getDrawable(int id) 从技术上讲是从 API 22 开始的(它仍然可以工作)。如果您想正确解决此问题并绕过弃用,您可以使用以下内容:

@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private Drawable getDrawableForSdkVersion(int resId, Resources res) {

    Drawable drawable = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        drawable = res.getDrawable(resId, null);
    } else {
        drawable = res.getDrawable(resId);
    }

    return drawable;

}

【讨论】:

    【解决方案2】:

    不推荐使用 API 22 的“getResources()”。您可以改用它,它还向后兼容,因此您可以安全地继续使用此方法。

    ContextCompat.getDrawable(context, R.drawable.<you_name_it>)
    

    更新:

    还忘了提到您可以使用 Picasso 将您的字符串(针对图片的路径)加载到图像视图中。

    这里有一个小例子:

    ImageView imageView1 = (ImageView) findViewById(R.id.myImageView);
    Picasso.with(getApplicationContext()).load("www.pictures.com/picture.jpg").into(imageView1);
    

    你可以在这里搜索一下毕加索:http://square.github.io/picasso/

    更不用说,Stackoverflow Android 应用也使用这个库,它是 Android 中必备的库之一。

    【讨论】:

    • 谢谢,但是如何动态访问我的图像?我想传递一个字符串,而不是静态的
    • 我可以在商业上使用毕加索吗?我说不出来
    • 你的图片来自哪里?
    • 本地的,我保存在drawable中
    • 没有声明毕加索不用于商业用途。
    【解决方案3】:
    ImageView imgView = (ImageView) findViewById(R.id.imageView);
    imgView.setImageDrawable(ContextCompat.getDrawable(currentActivity.this,R.drawable.your_image));
    

    其实theMatus回答了你的问题。此代码用于已弃用的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      相关资源
      最近更新 更多