2017-07-24 75 views
1

我有一個LinearLayout的水平方向,但是當它跨越一行中的4個元素時,它會繼續添加水平,我希望它自動更改爲下一行,例如:在LinearLayout的下一行添加圖像Programatcally - Android

會發生什麼: Whta happen:

我想要什麼: What I want:

我的代碼:

btnAdd.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      countLikesAdd++; 
      removeMessageOrShow(); 
      ImageView iconLike = new ImageView(Register30.this); 
      iconLike.setImageDrawable(getDrawable(R.drawable.musicicon)); 
      LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(140,130); 
      lp.setMargins(5,5,5,5); 
      iconLike.setLayoutParams(lp); 
      relativeLayout.addView(iconLike); 
     } 
    }); 

我的XML:

<ScrollView 
    android:id="@+id/svLikes" 
    android:layout_width="0dp" 
    android:layout_height="0dp" 
    android:layout_marginBottom="60dp" 
    android:layout_marginEnd="14dp" 
    android:layout_marginStart="14dp" 
    android:layout_marginTop="48dp" 
    android:background="#2f3342" 
    android:orientation="vertical" 
    app:layout_constraintBottom_toBottomOf="parent" 
    app:layout_constraintLeft_toLeftOf="parent" 
    app:layout_constraintRight_toRightOf="parent" 
    app:layout_constraintTop_toTopOf="@+id/btnAdd" 
    app:layout_constraintVertical_bias="0.0" 
    tools:layout_constraintBottom_creator="1" 
    tools:layout_constraintLeft_creator="1" 
    tools:layout_constraintRight_creator="1" 
    tools:layout_constraintTop_creator="1"> 
    <LinearLayout 
     android:id="@+id/linearLayout" 
     android:orientation="horizontal" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:padding="5dp" 
     android:paddingEnd="5dp" 
     android:paddingTop="5dp" 
     android:paddingLeft="5dp" 
     android:paddingRight="5dp" 
     > 
    </LinearLayout> 
</ScrollView> 

回答

0

LinearLayout不支持包裝到下一行,如果事情不適合的概念。

對於少數固定項目,最好的解決方案可能是在您執行谷歌搜索時使用許多「FlowLayout」庫中的一個。

對於大量項目(或您在設計時不知道的項目),可以使用RecyclerViewGridLayoutManager

+0

對。我發現它很好。 Thx回答! – Adolfok3

+2

考慮[FlexboxLayout](https://github.com/google/flexbox-layout) - 它既可以用於少量項目的手動佈局,也可以用於RecyclerView。 – ephemient

相關問題