2013-07-01 271 views
1

我正在將按鈕編程方式添加到linearLayout中。這很有效,直到我的按鈕超出屏幕寬度。有什麼辦法讓他們智能地翻轉到下一行?以編程方式將多個按鈕添加到佈局中

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 

    xmlns:tools="http://schemas.android.com/tools" 

    android:layout_width="match_parent" 

    android:layout_height="match_parent" 

    android:paddingBottom="@dimen/activity_vertical_margin" 

    android:paddingLeft="@dimen/activity_horizontal_margin" 

    android:paddingRight="@dimen/activity_horizontal_margin" 

    android:paddingTop="@dimen/activity_vertical_margin" 

    tools:context=".MainActivity" > 



    <LinearLayout 

     android:id="@+id/linearLayout1" 

     android:layout_width="wrap_content" 

     android:layout_height="wrap_content" 

     android:layout_alignParentLeft="true" 

     android:orientation="horizontal" 

     android:layout_alignParentTop="true" > 

    </LinearLayout> 



    <Button 

     android:id="@+id/button1" 

     android:layout_width="wrap_content" 

     android:layout_height="wrap_content" 

     android:layout_alignParentBottom="true" 

     android:layout_alignParentRight="true" 

     android:onClick="doThis" 

     android:text="Button" /> 



</RelativeLayout> 

我的onClick代碼:

public void doThis(View view){ 

Button myBtn = new Button(this); 

LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1); 

myBtn.setText("hello"); 

layout.addView(myBtn); 
} 

此代碼的工作,但添加第三個按鈕後,它開始走下車的畫面。任何意見,將不勝感激。

doThis後運行4次:

enter image description here

doThis運行10次後:

enter image description here

+0

有一個在Android的SDK(你可以通過一個共同的4.0虛擬機訪問它 - > API演示 - >動畫)樣品,並尋找它(我認爲這是稱爲自定義佈局或類似的東西)。在這個例子中,你可以看到如何在佈局中添加和包裝按鈕而不會出現拉伸不良。你應該看看 – Rob013

回答

0

LinearLayouts僅在單一方向上擴大(在你的情況下的水平),從而有沒有辦法讓它自動「換行」。如果你想要一個滾動條,你可以將它封裝在一個ScrollView中,但是它們仍然會在一行中。

更好的匹配你正在做的是一個GridView(http://developer.android.com/reference/android/widget/GridView.html)。您提供了一個ListAdapter,其中填充了組織到網格中的條目。

有可用的好GridView的例子在這裏:http://www.mkyong.com/android/android-gridview-example/

相關問題