如何从资源创buildDrawable
我有一个图像res/drawable/test.png (R.drawable.test)。 
 我想把这个图像传递给一个接受Drawable的函数。 
  (例如mButton.setCompoundDrawables()) 
 那么如何将图像资源转换为Drawable ? 
你的活动应该有方法getResources。 做:
 Drawable myIcon = getResources().getDrawable( R.drawable.icon ); 
此代码已被弃用。
 Drawable drawable = getResources().getDrawable( R.drawable.icon ); 
使用这个instad。
 Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon); 
  getDrawable (int id)方法从API 22开始折旧。 
 相反,您应该使用API 21+的getDrawable (int id, Resources.Theme theme) 
代码看起来像这样。
 Drawable myDrawable; if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){ myDrawable = context.getResources().getDrawable(id, context.getTheme()); } else { myDrawable = context.getResources().getDrawable(id); } 
我只想补充一点,如果在使用getDrawable(…)时得到“弃用”消息,应该使用支持库中的以下方法。
 ContextCompat.getDrawable(getContext(),R.drawable.[name]) 
使用此方法时,不必使用getResources()。
这相当于做类似的事情
 Drawable mDrawable; if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){ mDrawable = ContextCompat.getDrawable(getContext(),R.drawable.[name]); } else { mDrawable = getResources().getDrawable(R.id.[name]); } 
这适用于棒棒糖之前和之后的版本。
如果您试图从设置图像的视图中获取drawable,
 ivshowing.setBackgroundResource(R.drawable.one); 
那么drawable将只返回null值,下面的代码…
  Drawable drawable = (Drawable) ivshowing.getDrawable(); 
因此,如果您想从特定视图中检索绘图,最好使用以下代码设置图像。
  ivshowing.setImageResource(R.drawable.one); 
只有那样我们才可以完全转换drawable。