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

设置背景:

RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);

layout.setBackgroundResource(R.drawable.ready);

这是最好的方法吗?


慕森卡
浏览 430回答 3
3回答

MMTTMM

layout.setBackgroundResource(R.drawable.ready);是正确的。实现它的另一种方法是使用以下方法:final int sdk = android.os.Build.VERSION.SDK_INT;if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {&nbsp; &nbsp; layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );} else {&nbsp; &nbsp; layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));}但我认为问题出现是因为您正在尝试加载大图像。这是一个很好的教程如何加载大位图。更新:API级别22中不推荐使用的getDrawable(int)&nbsp;getDrawable(int )现在已在API级别22中弃用。您应该使用支持库中的以下代码:ContextCompat.getDrawable(context, R.drawable.ready)如果你引用ContextCompat.getDrawable的源代码,它会给你这样的东西:/**&nbsp;* Return a drawable object associated with a particular resource ID.&nbsp;* <p>&nbsp;* Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned&nbsp;* drawable will be styled for the specified Context's theme.&nbsp;*&nbsp;* @param id The desired resource identifier, as generated by the aapt tool.&nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; This integer encodes the package, type, and resource entry.&nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; The value 0 is an invalid identifier.&nbsp;* @return Drawable An object that can be used to draw this resource.&nbsp;*/public static final Drawable getDrawable(Context context, int id) {&nbsp; &nbsp; final int version = Build.VERSION.SDK_INT;&nbsp; &nbsp; if (version >= 21) {&nbsp; &nbsp; &nbsp; &nbsp; return ContextCompatApi21.getDrawable(context, id);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return context.getResources().getDrawable(id);&nbsp; &nbsp; }}关于ContextCompat的更多细节&nbsp;从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);

眼眸繁星

试试这个:layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));对于API 16 <:layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));

翻翻过去那场雪

RelativeLayout relativeLayout;&nbsp; //declare this globally现在,在onCreate,onResume等任何函数中relativeLayout = new RelativeLayout(this);&nbsp;&nbsp;relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image issetContentView(relativeLayout); //you might be forgetting this
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java
Android