Android自定义布局系列之一:流式布局(含TextView的点击事件)

前言:

    之前写了Unity优化方面的文章,之后就没写了。之后想把C盘扩大点,室友试了分区助手,很好用,也成功了,我心动也试了下,以为不会出什么意外,更不会出现数据丢失,抱着侥幸的心理没临时备份,哎!没想到最重要的E盘(所有资料)里所有资料都丢失了,之后用了数据恢复,卧槽,等资料全找回了,居然说要注册费100元,真的气死我了!!只好还原一年前的资料备份了,一场血淋淋的教训啊!


进入主题:

    在网上也找到了一些关于流失布局的好文章,但是好像没有添加点击事件,所以我在他们的基础上完善了下,添加了点击事件,接下来我将会贴出核心的源码!


MainActivity:

<span style="color:#330033;">package com.ysj.flowlayout;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private String mNames[] = { "考研", "求职", "面试 ", "四六级", "国二", "驾照", "电视剧",
			"电影", "小说", "美食", "游戏" };
	private int[] background = { R.drawable.blue, R.drawable.green,
			R.drawable.red, R.drawable.yellow };
	private XCFlowLayout mFlowLayout = null;
	private Context mContext = null;
	private List<TextView> tvs = null;

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

	private void init() {
		initData();
		initChildViews();
		initEvent();

	}

	private void initData() {
		mContext = this;
		tvs = new LinkedList<TextView>();
	}

	private void initChildViews() {

		mFlowLayout = (XCFlowLayout) findViewById(R.id.flowlayout);
		LayoutInflater mInflater = LayoutInflater.from(this);
		// MarginLayoutParams lp = new MarginLayoutParams(
		// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		// lp.leftMargin = 5;
		// lp.rightMargin = 5;
		// lp.topMargin = 5;
		// lp.bottomMargin = 5;
		Random random = new Random();
		for (int i = 0; i < mNames.length; i++) {
			TextView tv = (TextView) mInflater.inflate(R.layout.tv,
					mFlowLayout, false);
			tv.setText(mNames[i]);
			tv.setTextColor(Color.WHITE);
			tv.setTextSize(22);
			tv.setGravity(0);
			tv.setBackgroundResource(background[random.nextInt(4)]);
			tvs.add(tv);
			mFlowLayout.addView(tv);
		}
	}

	private void initEvent() {
		tvs.get(0).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Toast.makeText(mContext, "考研", Toast.LENGTH_SHORT).show();

			}
		});
	}

}</span>
CoustomFlowLayout:


<span style="color:#330033;">package com.ysj.flowlayout;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

/**
 *
 * @author ysj
 *
 */
public class CoustomFlowLayout extends ViewGroup {

    // 存储所有子View
    private List<List<View>> mAllChildViews = new ArrayList<>();
    // 每一行的高度
    private List<Integer> mLineHeight = new ArrayList<>();

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

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        // 父控件传进来的宽度和高度以及对应的测量模式
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        // 如果当前ViewGroup的宽高为wrap_content的情况
        int width = 0;// 自己测量的宽度
        int height = 0;// 自己测量的高度
        // 记录每一行的宽度和高度
        int lineWidth = 0;
        int lineHeight = 0;

        // 获取子view的个数
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            // 测量子View的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams();
            int childWidth = child.getMeasuredWidth() + lp.leftMargin
                    + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin
                    + lp.bottomMargin;
            // 换行时候
            if (lineWidth + childWidth > sizeWidth) {
                // 对比得到最大的宽度
                width = Math.max(width, lineWidth);
                height += lineHeight;
                // 重置lineWidth,lineHeight
                lineWidth = childWidth;
                lineHeight = childHeight;
            } else {// 不换行情况
                  // 叠加行宽
                lineWidth += childWidth;
                // 得到最大行高
                lineHeight = Math.max(lineHeight, childHeight);
            }
            // 处理最后一个子View的情况
            if (i == childCount - 1) {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }
        }
        // wrap_content
        setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth
                : width, modeHeight == MeasureSpec.EXACTLY ? sizeHeight
                : height);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        mAllChildViews.clear();
        mLineHeight.clear();
        // 获取当前ViewGroup的宽度
        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        // 记录当前行的view
        List<View> lineViews = new ArrayList<View>();
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child
                    .getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 如果需要换行
            if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width) {
                // 记录LineHeight
                mLineHeight.add(lineHeight);
                // 记录当前行的Views
                mAllChildViews.add(lineViews);
                // 重置行的宽高
                lineWidth = 0;
                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
                // 重置view的集合
                lineViews = new ArrayList<View>();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin
                    + lp.bottomMargin);
            lineViews.add(child);
        }
        // 处理最后一行
        mLineHeight.add(lineHeight);
        mAllChildViews.add(lineViews);

        // 设置子View的位置
        int left = 0;
        int top = 0;
        // 获取行数
        int lineCount = mAllChildViews.size();
        System.out.println("lineCount:"+lineCount);
        for (int i = 0; i < lineCount; i++) {
            // 当前行的views和高度
            lineViews = mAllChildViews.get(i);
            lineHeight = mLineHeight.get(i);
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
                // 判断是否显示
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child
                        .getLayoutParams();
                int cLeft = left + lp.leftMargin;
                int cTop = top + lp.topMargin;
                int cRight = cLeft + child.getMeasuredWidth();
                int cBottom = cTop + child.getMeasuredHeight();
                // 进行子View进行布局
                child.layout(cLeft, cTop, cRight, cBottom);
                left += child.getMeasuredWidth() + lp.leftMargin
                        + lp.rightMargin;
            }
            left = 0;
            top += lineHeight;
        }

    }

    /**
     * 与当前ViewGroup对应的LayoutParams
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }
}</span>

源码下载地址:http://pan.baidu.com/s/1i38ngwP


最后的最后:

    我试了下,给TextView设置id,继承OnClickListener,貌似实现点击事件时系统会去R文件里搜索ID,可是给TextView设置id没有写入R文件内,所以换了种方法实现,如果大家有更好的实现方法请多多指教哦!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值