背景:在android中使用大的背景图(ImageView)非常占用内存。如果背景图是激变或纯色,则直接设置颜色替代图片则非常有必要。一方面显示效果更有保证;二是内存会省下来不少呢~
方法一:布局设置背景图
1.添加布局文件
loading_bg.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:type="linear" android:startColor = "#105AA9" android:endColor = "#1B9FC5" android:angle="270"/> <corners android:radius="0dip"/> </shape>
2.引用
android:background="@drawable/loading_bg"
方法二:代码设置
1.创建view类
public class MyView extends View { public MyView(Context context) { super(context); } public MyView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //获取View的宽高 int width = getWidth(); int height = getHeight(); int colorStart = getResources().getColor(R.color.begin); int color1 = Color.GRAY; int colorEnd = getResources().getColor(R.color.end); Paint paint = new Paint(); LinearGradient backGradient = new LinearGradient(0, 0, 0, height, new int[]{colorStart ,colorEnd}, null, Shader.TileMode.CLAMP); paint.setShader(backGradient); canvas.drawRect(0, 0, width, height, paint); } }
2.引用
<cn.xx.xx.MyView android:layout_width="match_parent" android:layout_height="match_parent" />