2017-08-16 67 views
0

我有一個的LinearLayout:機器人:LinearLayout中與水平方向推壓關閉屏幕元件

<?xml version="1.0" encoding="utf-8"?> 
<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior"> 
    <LinearLayout 
     android:id="@+id/container" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal"> 

    </LinearLayout> 
</ScrollView> 

其中我填充動態添加片段

void add_item(){ 
     Database database = new Database(this); 
     String[] categories = database.getCategories(); 
     LinearLayout layout = (LinearLayout)findViewById(R.id.container); 
     FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
     if (categories.length>0) { 
      for (String category : categories){ 
       FrameLayout frame = new FrameLayout(this); 
       int id = View.generateViewId(); 
       frame.setId(id); 
       layout.addView(frame); 
       Fragment itemsFragment = CategoryFragment.newInstance(R.drawable.body, category); 
       ft.add(id, itemsFragment); 
      } 
      Log.i("test","success"); 
     } 
     ft.commit(); 
    } 

的問題是碎片離開屏幕。我實際上想要水平碎片,並且只在空間不足時移動到下面。可能嗎?

+0

如果你不改變線性佈局,以垂直的方向是什麼? –

+0

@AjilO。如果我這樣做,他們將排隊作爲列 –

+0

好吧。這是從剛剛讀書的問題once.To得到更好的反應很可能需要添加到你真正想要的水平碎片的問題,並在下面移動,只有當你運行的空間有點不清楚。 :) –

回答

1

的LinearLayout不能做到這一點很遺憾。您必須將每個視圖的所有寬度相加,然後當它們超出屏幕寬度時,請在下面創建一個新的LinearLayout並開始填充該寬度。不完全優雅。

爲了解決這個問題,谷歌創造了Flexbox的庫來模擬所需的行爲是在CSS中使用。 Take a look at it here

+0

我想我會做一個片段,因此它適合屏幕寬度,並改變方向爲垂直。後來我會嘗試你的方法。 –

0

首先 - 你的線性佈局的定位是「臥式」,所以它會試圖推動所有的孩子在一排,而不是列。

此外,你應該嘗試與RecyclerView工作,不因爲開銷存儲所有的意見,在內存中,讓他們繪製的LinearLayout。 Here is how to do it by Google