【问题标题】:getDrawable(int id) is deprecated. How can I set an image?getDrawable(int id) 已弃用。如何设置图像?
【发布时间】:2016-07-22 11:32:08
【问题描述】:

有一个问题! getDrawable() 在 API 22 中已弃用。所以,如果我使用 min API 16 制作应用程序,我该如何设置图像?

我看到我可以使用 getDrawable(int id, theme) ,但是这是在 API 21 中添加的,所以我不能使用它。

我试过setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.drawableName, null)) 但这也不起作用。使用 ContextCompat 或 getApplicationContext() 也不起作用。

private ImageView weatherIcon;
weatherIcon=(ImageView)findViewById(R.id.weatherIcon);
if(weatherReportList.size()>0){
            DailyWeatherReport report=weatherReportList.get(0);
            switch (report.getWeather()){
                case DailyWeatherReport.WEATHER_TYPE_CLOUDS:
                    weatherIcon.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.cloudy, null));
                    weatherIconMini.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.cloudy, null));
                case DailyWeatherReport.WEATHER_TYPE_RAIN:
                    weatherIcon.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.rainy));
                    weatherIconMini.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.rainy, null));

                default:
                    weatherIcon.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.sunny, null));
                    weatherIconMini.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.sunny, null));


            }

这不是该帖子的副本。我已经尝试了那里的所有方法,但都没有奏效。

【问题讨论】:

标签: android


【解决方案1】:

你可以使用

yourImageView.setImageDrawable(ContextCompat.getDrawable(context, /*your drawable like R.drawable.drawableName*/));

【讨论】:

  • 我通过 getContext 获取上下文?
  • 是的,如果是片段,你也可以使用getActivity(),如果是活动,则使用yourActivity.thisgetApplicationContext()
  • 但这也不起作用。 :( 也许我的代码有问题,但我不这么认为。
  • weatherIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.rainy));
  • 如果此代码在活动中,我总是建议将“this”作为上下文。
【解决方案2】:

你可以试试这个方法,

 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    return context.getResources().getDrawable(resource);
} else {
    return context.getResources().getDrawable(resource, null);
}

可以帮助你

【讨论】:

    【解决方案3】:

    我的项目似乎有错误,但我无法识别它。如果我尝试其他项目,它适用于上述任何答案。

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多