自定义ViewGroup——FlowLayout(标签式布局)的实现

从 http://blog.csdn.net/lmj623565791/article/details/38352503 ,【张鸿洋的博客】 学习了FlowLayout的编写。原文的onLayout()方法稍显复杂,用自己的方法试了一下。


先上最终效果图(逼死强迫症):



自定义ViewGroup来实现这样的布局

public class FlowLayout extends ViewGroup {
    private List<Integer> aboutChild = new ArrayList<>();
    private List<Integer> aboutLineHeight = new ArrayList<>();
    private boolean isFirstLayout = true;

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

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

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

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

        /*onMeasure()方法会执行多次,每次执行先清空List防止多次叠加出错*/
        aboutChild.clear();
        aboutLineHeight.clear();

        /*默认的sizeWidth和sizeHeight的大小以match_parent计算,如果实际设置为wrap_content
        则会在setMeasuredDimension()后设置*/
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        /*如果ViewGroup设置为wrap_content,则设置实际宽高为我们计算的width和height*/
        int width = 0;
        int height = 0;
        int lineWidth = 0;
        int lineHeight = 0;
        int count = getChildCount();
        /*每一行的子View数目*/
        int childNumOfLine = 0;

        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                /*child所占的宽高需要考虑它的margin*/
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

                /*如果超过了最大宽度(match_parent所得)*/
            if (lineWidth + childWidth > sizeWidth) {
                width = Math.max(lineWidth, width);
                height += lineHeight;
                lineHeight = childHeight;
                lineWidth = childWidth;
                aboutChild.add(childNumOfLine);
                childNumOfLine = 1;
                aboutLineHeight.add(lineHeight);
            } else {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
                childNumOfLine++;
            }
            if (i == count - 1) {
                width = Math.max(lineWidth, width);
                height += lineHeight;

                aboutChild.add(childNumOfLine);
                aboutLineHeight.add(lineHeight);
                Log.d("yzh", "aboutChild.size() = " + aboutChild.size());
            }
        }

        /*根据测量模式决定是否使用我们测得的宽高*/
        setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
                modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height);
    }


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

        /*避免多次执行*/
        if (isFirstLayout) {
            int left = 0;
            int top = 0;
            int childCursor = 0;
            for (int i = 0; i < aboutChild.size(); i++) {

                for (int j = 0; j < aboutChild.get(i); j++) {
                    View child = getChildAt(childCursor);

                    MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                    int lc = lp.leftMargin + left;
                    int tc = lp.topMargin + top;
                    int rc = lc + child.getMeasuredWidth();
                    int bc = tc + child.getMeasuredHeight();
                    left += lp.leftMargin + lp.rightMargin + child.getMeasuredWidth();
                    childCursor++;
                    child.layout(lc, tc, rc, bc);
                }
                left = 0;
                top += aboutLineHeight.get(i);
            }
            isFirstLayout = false;
        }
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

}

主要的难点就是onMeasure中换行以及宽高的计算,拿笔多画一画应该能想清楚。


我们用TextView来测试一下。首先去自定义一下TextView的style。在values下的styles.xml文件夹中添加如下style:

<style name="text_style" >
        <item name="android:textSize">20sp</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_margin">6dp</item>
        <item name="android:background">@drawable/text_back</item>
    </style>

里面还用到了自定义的background:

<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#665690a5" >
    </solid>

    <corners android:radius="8dp"/>
    
    <padding
        android:bottom="4dp"
        android:left="10dp"
        android:right="10dp"
        android:top="4dp" />
</shape>

最后在布局中:

    <com.example.yin.flowlayout.FlowLayout
        android:id="@+id/flow"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F2E18C">
        <TextView
            style="@style/text_style"
            android:text="Android"/>
        <TextView
            style="@style/text_style"
            android:text="ios"/>
        <TextView
            style="@style/text_style"
            android:text="other"/>
        <TextView
            style="@style/text_style"
            android:text="php"/>
        <TextView
            style="@style/text_style"
            android:text="WindowPhone"/>
        <TextView
            style="@style/text_style"
            android:text="Java"/>
        <TextView
            style="@style/text_style"
            android:text="c"/>
        <TextView
            style="@style/text_style"
            android:text="c++"/>
        <TextView
            style="@style/text_style"
            android:text="Window10"/>
        <TextView
            style="@style/text_style"
            android:text="c#"/>
        <TextView
            style="@style/text_style"
            android:text="Android"/>
        <TextView
            style="@style/text_style"
            android:text="ios"/>
        <TextView
            style="@style/text_style"
            android:text="other"/>
        <TextView
            style="@style/text_style"
            android:text="php"/>
        <TextView
            style="@style/text_style"
            android:text="WindowPhone"/>
        <TextView
            style="@style/text_style"
            android:text="Java"/>
        <TextView
            style="@style/text_style"
            android:text="c"/>
        <TextView
            style="@style/text_style"
            android:text="c++"/>
        <TextView
            style="@style/text_style"
            android:text="Window10"/>
        <TextView
            style="@style/text_style"
            android:text="c#"/>
    </com.example.yin.flowlayout.FlowLayout>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android自定义ViewGroup是指在Android开发中,通过继承ViewGroup类来创建自定义布局容器。自定义ViewGroup可以用于实现一些特殊的布局效果,比如侧滑菜单、滑动卡片等等。通过自定义ViewGroup,我们可以更灵活地控制子视图的布局和交互行为,以满足特定的需求。自定义ViewGroup实现主要包括重写onMeasure()方法和onLayout()方法,来测量和布局子视图。同时,我们还可以通过重写onInterceptTouchEvent()方法和onTouchEvent()方法来处理触摸事件,实现自定义的交互效果。如果你对自定义ViewGroup还不是很了解,或者正想学习如何自定义,可以参考相关的教程和文档,如引用\[1\]和引用\[2\]所提到的博客和官方文档。 #### 引用[.reference_title] - *1* [Android 手把手教您自定义ViewGroup(一)](https://blog.csdn.net/iteye_563/article/details/82601716)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [使用LayoutParams自定义安卓ViewGroup](https://blog.csdn.net/lfq88/article/details/127268493)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Android自定义ViewGroup](https://blog.csdn.net/farsight2009/article/details/62046643)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值