我需要根據按鈕是否適合水平方向來更改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);
}
}
});
}
這是第三個按鈕已經改變了自己以適應的方式。 我想要的結果是,如果所有按鈕都不能水平放置,請將方向更改爲垂直,以使按鈕彼此重疊。