如何将布局方向更改为垂直如果所有子视图都不适合水平方向
问题描述:
我需要根据按钮是否适合水平方向来更改Linearlayout的方向。例如,如果我们有两个按钮适合屏幕的整个宽度,我会用水平LinearLayout显示它们,但如果它们不适合,我需要以垂直布局显示它们。如何将布局方向更改为垂直如果所有子视图都不适合水平方向
我试过下面的代码,但因为第三个按钮调整自身大小,并开始垂直以适应边界,子计数结束仍然小于宽度。有没有一种方法来计算没有发生这种变化的按钮的宽度?
mButtonsLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
int childCount = mButtonsLayout.getChildCount();
int childWidth = 0;
for (int i = 0; i < childCount; i++) {
View child = mButtonsLayout.getChildAt(i);
childWidth += child.getWidth();
}
if (mButtonsLayout.getMeasuredWidth() < childWidth) {
mButtonsLayout.setOrientation(LinearLayout.VERTICAL);
} else {
mButtonsLayout.setOrientation(LinearLayout.HORIZONTAL);
}
ViewTreeObserver viewTreeObserver = mButtonsLayout.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.removeGlobalOnLayoutListener(this);
}
}
});
}
这是第三个按钮已经改变了自己以适应的方式。 我想要的结果是,如果所有按钮都不能水平放置,请将方向更改为垂直,以使按钮彼此重叠。
答
在这个library
<cn.lankton.flowlayout.FlowLayout
android:id="@+id/flowlayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
app:lineSpacing="10dp"
android:background="#F0F0F0">
</cn.lankton.flowlayout.FlowLayout>
gradle这个
compile 'cn.lankton:flowlayout:latest version'
这里是另一个库安排视图的programetically看看..