2017-02-24 30 views
0

我在一件事上掙扎。比方說,我有線性佈局,設置高度和寬度是match_parent。我將擁有一定數量的視圖1到6,並且在運行時我不知道我將從服務器接收多少數據。問題是,我如何在佈局中對它們進行排序,以便根據存在的視圖數量來縮放它們的寬度?如果有超過3個視圖,我需要把它們分成兩行。 this is how it should look like根據視圖數量排列視圖中的視圖

我正在考慮使用佈局權重,但不能考慮解決方案,可以把它們放到兩行。有任何想法嗎 ?

回答

0

您必須動態添加視圖到線性佈局。

首先在xml中創建容器佈局。

<LinearLayout 
    android:id="@+id/containerLayout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
/> 

然後檢查,

if(list.size()<=3) 
    { 
     Then assign weight to container. i.e weight=list.size 

      for(int i=0;i<size;i++) 
      { 
      TextView textview = new TextView(this); 
      textview.setText(brandName); 
      textview.setWeight(1f); 

      container.addView(textview); 
      } 
    } 
    else 
    { 

     int totalRows= (list.size/3)+(list.size%3); 
     int count=0; 

     for(int i=0;i<totalRows;i++) 
     { 
       LinearLayout newLL = new LinearLayout(mContext); 
       newLL.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); 
       newLL.setOrientation(LinearLayout.HORIZONTAL); 

       for(int j=count;j<count+3;j++) 
       { 
        count++; 
        TextView textview = new TextView(this); 
        textview.setText(brandName); 
        newLL.addView(textview); 
       } 
       container.addView(newLL); 
     } 

    } 

你必須做一些像this.This是不實際的代碼。

+0

這實際上可以工作,非常感謝你 – Traabefi

+0

請接受答案。 – Ragini