2017-05-03 62 views
1

我需要根據按鈕是否適合水平方向來更改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); 
       } 
      } 
     }); 
    } 

這是第三個按鈕已經改變了自己以適應的方式。 我想要的結果是,如果所有按鈕都不能水平放置,請將方向更改爲垂直,以使按鈕彼此重疊。

enter image description here

回答

2

在這個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' 

enter image description here

這裏是另一個庫安排視圖的programetically看看..

FlexBox

2

這不回答你的問題,但我認爲這是一個非常好的選擇,以達到你想。

使用谷歌的flexbox-layout它允許你自動排列按鈕,如果沒有地方水平。

希望這將是有用的

相關問題