Bla*_*icz 145 resources android drawable android-context
我需要让Drawable对象显示在图像按钮上.有没有办法使用下面的代码(或类似的东西)从android.R.drawable.*包中获取对象?
例如,如果drawableId是android.R.drawable.ic_delete
mContext.getResources().getDrawable(drawableId)
Run Code Online (Sandbox Code Playgroud)
Pet*_*ton 206
Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);
Run Code Online (Sandbox Code Playgroud)
Muh*_*man 104
从API 21开始,您应该使用该getDrawable(int, Theme)方法而不是getDrawable(int),因为它允许您获取drawable与resource ID给定的特定对象关联的对象screen density/theme.调用该deprecated getDrawable(int)方法相当于调用getDrawable(int, null).
您应该使用支持库中的以下代码:
ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Run Code Online (Sandbox Code Playgroud)
使用此方法相当于调用:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
Run Code Online (Sandbox Code Playgroud)
小智 9
从API 21开始,您还可以使用:
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
Run Code Online (Sandbox Code Playgroud)
代替 ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
所以现在你需要使用
ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)
Run Code Online (Sandbox Code Playgroud)
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.core.content.res.ResourcesCompat
object ResourceUtils {
fun getColor(context: Context, color: Int): Int {
return ResourcesCompat.getColor(context.resources, color, null)
}
fun getDrawable(context: Context, drawable: Int): Drawable? {
return ResourcesCompat.getDrawable(context.resources, drawable, null)
}
}
Run Code Online (Sandbox Code Playgroud)
使用这种方法,例如:
Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)
image.setImageDrawable(img);
Run Code Online (Sandbox Code Playgroud)
最好的办法是
button.setBackgroundResource(android.R.drawable.ic_delete);
Run Code Online (Sandbox Code Playgroud)
或者使用以下代码绘制可绘制左、上、右、下。在这种情况下我设置了drawable left。
int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
Run Code Online (Sandbox Code Playgroud)
和
getResources().getDrawable()现已弃用
| 归档时间: |
|
| 查看次数: |
137856 次 |
| 最近记录: |