2016-07-22 17 views
0

有疑問! getDrawable()在API 22中已棄用。因此,如果我使用min API 16創建應用程序,如何設置圖像?getDrawable(int id)已棄用。我如何設置圖像?

我看到我可以使用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)); 


      } 

這不是該帖子的副本。我已經嘗試過所有的方法,但沒有一個能夠工作。

+0

檢查這裏:http://stackoverflow.com/a/29041466/3626214 – Aspicas

+0

可能重複的[Android的getResources()。getDrawable()不贊成API 22](http://stackoverflow.com/questions/29041027/android -getresources-getdrawable-deprecated-api-22) –

+0

儘管'getDrawable()'不推薦使用,但它現在仍然可以正常工作,所以可能在其他地方的代碼中有錯誤 – Harlan

回答

0

你可以試試這個方法,

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

5可以幫助您

3

可以使用

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

而且我通過getContext獲取上下文? –

+0

是的,你可以,如果它是片段或'yourActivity.this'或'getApplicationContext()'活動,你也可以使用'getActivity()'。 –

+0

但是這也行不通。 :(或許我的代碼有問題,但我不這麼認爲。 –

0

看來,我的項目有一個錯誤,但我不能確定它。如果我嘗試其他項目,它可以與上面的任何答案一起使用。