tXXX属性来实现约束?

使用ConstraintLayout时,app:layout_constraintXXX属性是必须的,用于定义子视图之间的约束关系。如果不设置这些属性,则子视图会默认放置在左上角,不会具有任何约束关系。

如果想要不需要设置app:layout_constraintXXX属性来实现约束,可以使用自定义ViewGroup来实现。自定义ViewGroup可以通过重写onMeasure()和onLayout()方法来实现子视图的测量和布局。

例如,可以使用自定义ViewGroup来实现一个简单的约束布局:

public class MyConstraintLayout extends ViewGroup {
    
    public MyConstraintLayout(Context context) {
        super(context);
    }

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int maxWidth = 0;
        int maxHeight = 0;

        // 测量子视图的大小
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
            maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
        }

        // 设置自身大小
        setMeasuredDimension(widthSize, heightSize);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // 布局子视图
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
        }
    }
}

此时,在使用MyConstraintLayout时就不需要设置app:layout_constraintXXX属性了,而是通过在代码中调用addView()方法来添加子视图,并在onLayout()方法中根据需要布局。

MyConstraintLayout myConstraintLayout = new MyConstraintLayout(context);
TextView textView = new TextView(context);
Button button = new Button(context);
myConstraintLayout.addView(textView);
myConstraintLayout.addView(button);
// 设置子视图约束
// ...
``
ConstrainLayout虾Android自定义view 如何不需要设置applayout_constrain

原文地址: https://www.cveoy.top/t/topic/hrCv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录