如何在android中设置背景,如何在Android中以编程方式设置背景可绘制

c590f09268c2f2bdeadbe2b44475823f.png

MMTTMM

layout.setBackgroundResource(R.drawable.ready);是正确的。实现它的另一种方法是使用以下方法:final int sdk = android.os.Build.VERSION.SDK_INT;if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {    layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );} else {    layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));}但我认为问题出现是因为您正在尝试加载大图像。这是一个很好的教程如何加载大位图。更新:API级别22中不推荐使用的getDrawable(int) getDrawable(int )现在已在API级别22中弃用。您应该使用支持库中的以下代码:ContextCompat.getDrawable(context, R.drawable.ready)如果你引用ContextCompat.getDrawable的源代码,它会给你这样的东西:/** * Return a drawable object associated with a particular resource ID. *

 * Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned * drawable will be styled for the specified Context's theme. * * @param id The desired resource identifier, as generated by the aapt tool. *            This integer encodes the package, type, and resource entry. *            The value 0 is an invalid identifier. * @return Drawable An object that can be used to draw this resource. */public static final Drawable getDrawable(Context context, int id) {    final int version = Build.VERSION.SDK_INT;    if (version >= 21) {        return ContextCompatApi21.getDrawable(context, id);    } else {        return context.getResources().getDrawable(id);    }}关于ContextCompat的更多细节 从API 22开始,您应该使用该getDrawable(int, Theme)方法而不是getDrawable(int)。更新:如果您使用的是支持v4库,则以下内容对所有版本都足够了。ContextCompat.getDrawable(context, R.drawable.ready)您需要在app build.gradle中添加以下内容compile 'com.android.support:support-v4:23.0.0' # or any version above或者在以下任何API中使用ResourceCompat:import android.support.v4.content.res.ResourcesCompat;ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值