自定义View,流式布局,

本文详细解析了自定义FlowLayout布局的实现原理,包括如何通过遍历子View进行布局计算,以及如何处理换行和控件位置调整。同时,介绍了如何在XML文件中使用自定义控件,以及如何通过代码动态添加TextView到FlowLayout中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

写的比较基础, 备忘使用。

public class FlowLayout extends ViewGroup {


    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 onLayout(boolean changed, int l, int t, int r, int b) {
        //测量所有子View的总高度
        measureChildren(0, 0);

        //当前行前面所有控件宽度
        int allWidth = 0;
        //当前行前面所有控件高度
        int allHeight = 0;

        //遍历所有子View
        for (int i = 0; i < getChildCount(); i++) {
            //拿到子控件
            View view = getChildAt(i);

            //先判断是否换行, 如果控件在一行放不下,便放入下一行
            if (allWidth + view.getMeasuredWidth() >= getMeasuredWidth()) {
                //换行
                //换行的时候,前面的总宽度重新设置为0,宽度加上一行的高度
                allWidth = 0;
                //高度加上之前的高度
                allHeight += view.getMeasuredHeight();
            }

            //换行时变高度, 不换行时只变宽度
            //设置前后左右的控件的位置 , 属性先后顺序是:左上右下
            view.layout(allWidth,
                    allHeight,
                   allWidth + view.getMeasuredWidth(),
                   allHeight + view.getMeasuredHeight());

            //之前总宽度加上这次的宽度, 等于最新的宽度
            allWidth += view.getMeasuredWidth();
        }


    }
}

 

如果写的死数据,可以在xml文件中自定义控件添加Textview ,

可以使用shape绘制一个圆角边框, 使用backbackground 引用圆角

删除所有视图  group的方法,  removeViews;

 

select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                TextView  textView = new TextView(HomePageActivity.this);
                //设置输出框的值
                String s = home_edit.getText().toString();
                textView.setText(s);
                //设置背景
                textView.setBackgroundResource(R.drawable.bg);
                ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                //设置padding
                textView.setPadding(10, 0, 10, 10);
                //设置margins
                layoutParams.setMargins(10, 10, 10, 10);
                textView.setLayoutParams(layoutParams);

                flow_layout.addView(textView);
            }
        });

 

//将ui中的px转为dp
int dp_20 = getResources().getDimensionPixelSize(R.dimen.dp_20);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值