android 自定义控件之又一个简单的loading框

   新的需求还是木有下来,今天再次写出一个loading框,恩,就是下面这个样子,

   

   可以看到,效果是比较简单的,看上去是在旋转,而实际上只是每一个竖杠不停的改变自己的长度而已,老规矩,还是先上代码

  

public class BarLoading extends View {
private int maxLen = 0;   //最大的竖杠长度
private int viewWidth;   //控件的宽度
private int viewHeight;  //控件的高度
private Paint mPaint = new Paint();
   private int[] allSize = new int[5]; //竖杠全部的可能高度
private int[] length = new int[12]; //没个竖杠的高度对应在全部竖杠高度的角标
private boolean[] isIncrease = new boolean[]{false, false, false, false, true, true, true,
true, false, false, false, false}; //这个竖杠在下一步应该边长还是变短

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
invalidate();
}
};

public BarLoading(Context context) {
this(context, null);
}

public BarLoading(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public BarLoading(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaint();
}

private void initPaint() {
mPaint.setColor(Color.parseColor("#ff0000"));
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(10);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
viewWidth = MeasureSpec.getSize(widthMeasureSpec);
viewHeight = MeasureSpec.getSize(heightMeasureSpec);
maxLen = viewHeight - 70;
intLength();
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

private void intLength() {
int j = 0;
for (int x = 0; x < 5; x++) {
allSize[x] = maxLen * (x + 1) / 5;
}
for (int i = 0; i < 12; i++) {
if (i <= 4 || i >= 9) j++;
else j--;
length[i] = j - 1;
}
Log.i("hugy", length.toString());
}

@Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < 12; i++) {
canvas.drawLine(viewWidth / 12 * (i + 1), (viewHeight - allSize[length[i]]) / 2,
viewWidth / 12 * (i + 1), (viewHeight - allSize[length[i]]) / 2 +
allSize[length[i]], mPaint);
}
super.onDraw(canvas);
}

public void startLoading() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
int[] mid = new int[12];
for (int i = 0; i < 12; i++) {
if (length[i] == 4) {
isIncrease[i] = false;
} else if (length[i] == 0) {
isIncrease[i] = true;
}
if (isIncrease[i]) {
mid[i] = length[i] + 1;
} else {
mid[i] = length[i] - 1;
}

}
length = mid;
Log.i("hugy", length.toString());
mHandler.obtainMessage(1).sendToTarget();
}
};
timer.schedule(task, 100, 200);
}
}

  可以看到,我这里总共设置了12条竖杠,竖杠长度的可能值总共有5个。
  onMeasure方法里主要获得了maxLen,allSize,lengths值,主要是为初始化控件的时候画杠准备的;
  onDraw方法没什么好说的,就是循环画了12个杠,杠的长度根据allSize和lengths结合可以得到;
  主要的就是startLoading这个方法里的逻辑了,其实也没什么,就是在lengths脚标为4(allSize只有5个值)时,让isIncrease[] 里对应的boolean值变为false,表示下一次,这个杠要开始变短,
lengths脚标为0时,对应的boolean值变为true就好了,然后呢,就可以根据对应的isIncrease的boolean值,来判断lengths对应的角标的变化是增大还是减小;
  恩,基本就是这样,这次的总结就到这里!!

posted on 2017-06-28 16:36  秦家十月  阅读(1852)  评论(0编辑  收藏  举报

导航