美文网首页
Android实现流式布局

Android实现流式布局

作者: 背锅TV丶伴奏大师 | 来源:发表于2022-05-27 14:27 被阅读0次

1.使用flexboxLayout

implementation 'com.google.android:flexbox:3.0.0'//Android官方流式布局
<com.google.android.flexbox.FlexboxLayout
            android:id="@+id/flexBox"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:alignContent="stretch"
            app:alignItems="stretch"
            app:flexDirection="row"
            app:flexWrap="wrap"
            app:justifyContent="flex_start"
            app:layout_constraintTop_toBottomOf="@+id/tv_position"
            app:maxLine="2" />
flexboxLayout=findViewById(R.id.flexBox);
flexboxLayout.removeAllViews();
flexboxLayout.addView(createTextView(str));
private TextView createTextView(final String str) {
        final TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(str);
        textView.setTextSize(12);
        textView.setTextColor(getResources().getColor(R.color.blue));
        textView.setBackgroundResource(R.drawable.bg2_blue2_r20);
        int paddingVertical = XUtils.dp2px(2);
        int paddingHorizontal = XUtils.dp2px(8);
        ViewCompat.setPaddingRelative(textView, paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int marginHorizontal = XUtils.dp2px(6);
        int marginTop = XUtils.dp2px(6);
        layoutParams.setMargins(marginHorizontal, marginTop, marginHorizontal, 0);
        textView.setLayoutParams(layoutParams);
        return textView;
    }

2.使用recyclerview+FlexboxLayoutManager

implementation 'com.google.android:flexbox:3.0.0'//Android官方流式布局
FlexboxLayoutManager layoutManager=new FlexboxLayoutManager(this);
layoutManager.setFlexDirection(FlexDirection.ROW);
//layoutManager.setJustifyContent(JustifyContent.CENTER);
//layoutManager.setAlignItems(AlignItems.CENTER);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setAdapter(adapter);

相关文章

网友评论

      本文标题:Android实现流式布局

      本文链接:https://www.haomeiwen.com/subject/wrwmprtx.html