Android getResources().getDrawable() 在API 22中已被弃用

849

随着新的安卓API 22,getResources().getDrawable() 现在已经被弃用。

现在最好的方法是仅使用 getDrawable() 来获取Drawable对象。

发生了什么变化?


你能具体说明你的问题吗?Resources类的方法getDrawable(int id)被弃用了。现在你应该使用带有新主题参数的方法getDrawable(int id,Resources.Theme theme) - code monkey
2
ContextCompat.getDrawable(context, R.color.color_name) - Ashokchakravarthi Nagarajan
您可以查看我的博客文章,了解更详细的说明,为什么Resources#getDrawable(int)Resources#getColor(int)都已被弃用。 - Alex Lockwood
1
Google 应该为每个已弃用的函数提供快速修复。我在这里发了一篇帖子:https://code.google.com/p/android/issues/detail?id=219495 - android developer
16个回答

1

试试这个:

public static List<ProductActivity> getCatalog(Resources res){
    if(catalog == null) {
        catalog.add(new Product("Dead or Alive", res
                .getDrawable(R.drawable.product_salmon),
                "Dead or Alive by Tom Clancy with Grant Blackwood", 29.99));
        catalog.add(new Product("Switch", res
                .getDrawable(R.drawable.switchbook),
                "Switch by Chip Heath and Dan Heath", 24.99));
        catalog.add(new Product("Watchmen", res
                .getDrawable(R.drawable.watchmen),
                "Watchmen by Alan Moore and Dave Gibbons", 14.99));
    }
}

虽然这段代码可能回答了问题,但是提供关于为什么和/或如何回答问题的额外上下文可以提高其长期价值。 - Donald Duck

0

英文 API 等级 14

marker.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.miubicacion, null));

你应该在回答中提供更多的上下文。 - picsoung

0

如果您需要从针对SDK 23及以上的其他应用程序获取可绘制对象

PackageManager manager = getApplicationContext().getPackageManager();
Resources resources = null;
try {
    resources = manager.getResourcesForApplication("com.anyapp");
    } 
catch (PackageManager.NameNotFoundException e) {
   e.printStackTrace();
   }
assert resources != null;
Drawable notiIcon = ResourcesCompat.getDrawable(resources, current.iconId/* drawable resource id */, null);

0

现在你需要实现像这样

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
        //
    } else {
        //
    }

只需要以下一行代码,ContextCompat.getDrawable会处理所有事情

ContextCompat.getDrawable(this, R.drawable.your_drawable_file)

0
对于一些人来说,即使在应用本文中提出的建议后仍然存在问题(我曾经也是这样),请在你的应用程序类Application中的onCreate()方法中添加以下代码行。

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)

此处此处所建议的,有时需要这样做才能从资源中访问向量,特别是当您处理菜单项等内容时。


-2

Build.VERSION_CODES.LOLLIPOP 现在应该更改为 BuildVersionCodes.Lollipop,即:

if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) {
    this.Control.Background = this.Resources.GetDrawable(Resource.Drawable.AddBorder, Context.Theme);
} else {
    this.Control.Background = this.Resources.GetDrawable(Resource.Drawable.AddBorder);
}

“BuildVersionCodes”不是Xamarin特有的类吗? - Ted Hopp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接