对于新的android API 22,getResources().getDrawable()现在已被弃用。现在最好的方法是只使用getDrawable()。

什么改变了?


当前回答

现在您需要这样实现

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

只需执行一行代码就足够了,ContextCompat.getDrawable将处理所有问题

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

其他回答

如果您需要从其他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);

现在您需要这样实现

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

只需执行一行代码就足够了,ContextCompat.getDrawable将处理所有问题

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

试试这个

ContextCompat.getDrawable(getActivity(), R.drawable.drawable_resource_name);

en-api级别14

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

这只是我如何在数组中修复问题以加载listView的一个示例,希望它有所帮助。

 mItems = new ArrayList<ListViewItem>();
//    Resources resources = getResources();

//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.az_lgo), getString(R.string.st_az), getString(R.string.all_nums)));
//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.ca_lgo), getString(R.string.st_ca), getString(R.string.all_nums)));
//    mItems.add(new ListViewItem(resources.getDrawable(R.drawable.co_lgo), getString(R.string.st_co), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.az_lgo, null), getString(R.string.st_az), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.ca_lgo, null), getString(R.string.st_ca), getString(R.string.all_nums)));
    mItems.add(new ListViewItem(ResourcesCompat.getDrawable(getResources(), R.drawable.co_lgo, null), getString(R.string.st_co), getString(R.string.all_nums)));