简单自定义View流式布局实现模版

本文介绍了一个名为HotSearch的自定义视图组件,该组件用于实现类似热门搜索标签的功能。它通过继承ViewGroup并重写onMeasure和onLayout方法来布局内部的子视图,同时提供了点击监听以获取被点击的文本。
package com.example.jingdong.FirstPages.FirstPageSearchs;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.example.jingdong.Application.ImageLoaderApp;

/**
 * Created by Administrator on 2017/12/8 0008.
 */

public class HotSearch extends ViewGroup{
    private HotInterface hotInterface;
    public void getString(HotInterface hotInterface){
        this.hotInterface = hotInterface;
    }
    public HotSearch(Context context) {
        super(context);
    }

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        /**
         * 一般是定义为int top;一个top实际上是数组的下标
         left : 指定矩形框左上角的x坐标
         top: 指定矩形框左上角的y坐标
         right: 指定矩形框右下角的x坐标
         bottom:指定矩形框右下角的y坐标
         */
        int width = getWidth();
        int height = getHeight();
        int tw = 0;
        int th = 0;
        for (int t = 0; t < getChildCount(); t++) {
            final View child = getChildAt(t);
            if (tw + child.getWidth() < width) {

            } else {
                tw = 0;
                th += child.getMeasuredHeight();   //超过屏幕的宽度,自动换行
            }

            child.layout(tw, th, tw + child.getMeasuredWidth(), th + child.getMeasuredHeight());
            tw += child.getMeasuredWidth();
            child.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {

                    Button bt = (Button) child;
                    String s = bt.getText().toString();
                    int r = 0;
                    if(ImageLoaderApp.oldarr!=null){
                        for(int i=0;i<ImageLoaderApp.oldarr.size();i++){
                            if(ImageLoaderApp.oldarr.get(i).equals(s)){
                                r = 1;
                            }
                        }
                    }
                    if(r==0){
                        ImageLoaderApp.oldarr.add(s);
                    }
                    hotInterface.getText(s);

                }
            });
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值