实现碰撞ViewGroup,任何其中的子view都可以实现碰撞移动

上一篇博客已经实现了一个固定view来展示碰撞算法—简单碰撞算法及其demo(屏幕气泡原理),今天做了一个相对负责的ViewGroup,即放在其中的每个view都可以自动去”飘动”!为其子view实现碰撞算法!
下面先看一下实现后的效果!
这里写图片描述

原理分析:
1.需自定义一个ViewGroup来存放所有的子view,但是每个子view的移动角度移动速度移动边界等信息是不同的,所以需要自定义一个helper类来存储每一个子view的移动范围,速度大小和速度方向以及位置信息!
2.根据子view的个数,在ViewGroup中新建helper对象.
3.不断更新每个子view的位置信息,在ViewGroup的onlayout中不断更新位置

代码实现过程:
1.新建一个ViewGroup来存放所有的子view

package com.example.automoveviewgroup;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;

@SuppressLint("DrawAllocation")
public class AutoMoveViewGroup extends RelativeLayout {
   

    private List<AutoMoveHelper> mAutoMoveHelpers;// 用于存放每一个子view对应的helper类

    public AutoMoveViewGroup(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

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

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

    private void init() {
        mAutoMoveHelpers = new ArrayList<>();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int wideMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width, height;
        if (wideMode == MeasureSpec.AT_MOST) {
            width = 600;
        } else {
            width = MeasureSpec.getSize(widthMeasureSpec);
        }

        if (heightMode == MeasureSpec.AT_MOST) {
            height = 600;
        } else {
            height = MeasureSpec.getSize(heightMeasureSpec);
        }

        setMeasuredDimension(width, height);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        requestLayout();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值