自定义ViewGroup实现三色梯形布局

效果图

首先创建ThreeColorLayout类继承ViewGroup
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class ThreeColorLayout extends ViewGroup {
    //声明点击事件对象
    private ChildClickListener childClickListener;

    public ThreeColorLayout(Context context) {
        super(context);
    }

    public ThreeColorLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

    /**
     * 测量
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //子view摆放的起始位置
        int allLeft = 0;
        //存储所有行的高度相加,用于确定此容器的高度
        int allHeight = 0;
        //测量子View的宽高
        int childCount = getChildCount();
        //判断childCount,防止childCount为0遍历报错
        if (childCount > 0) {
            //遍历子控件
            for (int i = 0; i < childCount; i++) {
                //得到子控件
                View child = getChildAt(i);
                //测量子View高
                allHeight += child.getMeasuredHeight();
                //给子控件添加测量标准
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
        //获取屏幕宽度
        DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
        //子控件最大宽度是屏幕宽度
        allLeft = metrics.widthPixels;
        //设置ThreeColorLayout容器的宽高
        setMeasuredDimension(allLeft, allHeight);
    }

    /**
     * 布局
     *
     * @param changed
     * @param l            * @param t            * @param r            * @param b            */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //测量子View的宽高
        int childCount = getChildCount();
        //子view摆放的起始位置
        int allLeft = 0;
        //存储所有行的高度相加,用于确定此容器的高度
        int allHeight = 0;
        //遍历子View
        for (int i = 0; i < childCount; i++) {
            //获取子View
            View child = getChildAt(i);
            //子View的摆放位置
            child.layout(allLeft, allHeight, allLeft + child.getMeasuredWidth(), allHeight + child.getMeasuredHeight());
            //摆放子view
            allLeft += getChildAt(i).getMeasuredWidth();
            allHeight += child.getMeasuredHeight();
            //屏幕宽度
            DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
            int widthPixels = metrics.widthPixels;
            //判断子View宽度是否大于屏幕宽度,大于则换行
            if (allLeft + child.getMeasuredWidth() > widthPixels) {
                //子View初始位置归0,回到最左边
                allLeft = 0;
            }
            //给子View添加点击事件
            child.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    TextView textView = (TextView) v;
                    //实现自定义接口
                    childClickListener.childClick(textView);
                }
            });
            //给子View添加长按事件
            child.setOnLongClickListener(new OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    TextView textView = (TextView) v;
                    Toast.makeText(getContext(), textView.getText().toString(), Toast.LENGTH_SHORT).show();
                    //长按删除子View
                    removeView(v);
                    return true;
                }
            });
        }
    }

    /**
     * 点击事件暴露给外面使用
     *
     * @param childClickListener
     */
    public void setChildClickListener(ChildClickListener childClickListener) {
        this.childClickListener = childClickListener;
    }

    /**
     * 点击事件接口
     */
    public interface ChildClickListener {
        void childClick(View v);
    }
}

在布局文件里应用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <Button
        android:id="@+id/addbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="增加"
        android:layout_alignParentRight="true"/>
    <example.com.lianxi20180529.ThreeColorLayout
        android:id="@+id/mvg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:layout_below="@+id/btn">

    </example.com.lianxi20180529.ThreeColorLayout>
</RelativeLayout>
在MainActivity中设置......
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ThreeColorLayout mMvg;
    /**
     * 增加
     */
    private Button mAddbtn;
    private int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        mMvg = (ThreeColorLayout) findViewById(R.id.mvg);
        mAddbtn = (Button) findViewById(R.id.addbtn);
        mAddbtn.setOnClickListener(this);
        //设置点击事件
        mMvg.setChildClickListener(new ThreeColorLayout.ChildClickListener() {
            @Override
            public void childClick(View v) {
                TextView textView = (TextView) v;
                String str = textView.getText().toString();
                Toast.makeText(MyApp.context, textView.getText().toString(), Toast.LENGTH_SHORT).show();
                Log.e("TextView -------->", str);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.addbtn:
                ++count;
                //获取屏幕宽度
                DisplayMetrics metrics = this.getResources().getDisplayMetrics();
                int widthPixels = metrics.widthPixels;
                TextView tv = new TextView(MyApp.context);
                //设置控件文本
                tv.setText(count + "");
                //设置控件文本居中显示
                tv.setGravity(Gravity.CENTER);
                //设置控件文本字体颜色
                tv.setTextColor(Color.BLACK);
                //设置控件背景颜色
                if (count % 3 == 1) {
                    tv.setBackgroundColor(Color.RED);
                } else if (count % 3 == 2) {
                    tv.setBackgroundColor(Color.YELLOW);
                } else {
                    tv.setBackgroundColor(Color.BLUE);
                }
                //给控件添加平移动画
                ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(tv, "translationX", (widthPixels - widthPixels / 3), 0f);
                objectAnimator.setDuration(1000);
                objectAnimator.start();
                //添加子View
                mMvg.addView(tv);
                //得到view的属性参数
                ViewGroup.LayoutParams params = tv.getLayoutParams();
                //设置子View宽高----宽是屏幕的1/3
                params.width = widthPixels / 3;
                params.height = 50;
                tv.setLayoutParams(params);
                Log.e("TextView -------->", tv.getText().toString());
                break;
        }
    }
}
完成*********


猜你喜欢

转载自blog.csdn.net/qq_42081816/article/details/80518699