Use*_*337 272 android drawable
我有一个图像res/drawable/test.png(R.drawable.test).
我想将此图像传递给接受的函数Drawable.
(例如mButton.setCompoundDrawables())
那么如何将图像资源转换为Drawable?
Jem*_*ems 548
您的Activity应该具有getResources方法.做:
Drawable myIcon = getResources().getDrawable( R.drawable.icon );
Run Code Online (Sandbox Code Playgroud)
dan*_*kas 130
不推荐使用此代码:
Drawable drawable = getResources().getDrawable( R.drawable.icon );
Run Code Online (Sandbox Code Playgroud)
请改用:
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
Run Code Online (Sandbox Code Playgroud)
Chr*_*ell 23
该getDrawable (int id)方法从API 22开始折旧.
相反,你应该使用getDrawable (int id, Resources.Theme theme)for API 21+
代码看起来像这样.
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 13
我想补充一点,如果在使用getDrawable(...)时收到"已弃用"消息,则应使用支持库中的以下方法.
ContextCompat.getDrawable(getContext(),R.drawable.[name])
Run Code Online (Sandbox Code Playgroud)
使用此方法时,您不必使用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]);
}
Run Code Online (Sandbox Code Playgroud)
这适用于Lollipop前后版本.
从向量资源获取 Drawable,无论其是否为向量:
AppCompatResources.getDrawable(context, R.drawable.icon);
Run Code Online (Sandbox Code Playgroud)
注意:
ContextCompat.getDrawable(context, R.drawable.icon);将为android.content.res.Resources$NotFoundException矢量资源生成。
| 归档时间: |
|
| 查看次数: |
229133 次 |
| 最近记录: |