2012-01-10 89 views
0

所以我想要做的是將按鈕添加到LinearLayout programaticalls,這工作正常。我希望他們能夠衝擊片雷管,按鈕的一條線在水平順序,所以我設置的LinearLayout是這樣的:當以編程方式添加按鈕時調整父LinearLayout的大小

<LinearLayout 
android:id="@+id/button_frame" 
android:orientation="horizontal" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content"> 

</LinearLayout> 

然後我添加的按鈕編程:

for (String text: textlist) { 

     Button cbut = new Button(context); 
     cbut.setText(text); 
     cbut.setLayoutParams(new ViewGroup.LayoutParams(
       ViewGroup.LayoutParams.WRAP_CONTENT, 
       ViewGroup.LayoutParams.WRAP_CONTENT)); 
     cbut.setOnClickListener(new Button.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       Log.d(LOGTAGNAME, "TEST: " + buttonText); 
      } 
     }); 

     button_frame.addView(cbut); 
     button_frame.invalidate(); 
    } 

這工作,直到按鈕延長屏幕寬度。所以我想要發生的是,如果按鈕擴展了屏幕寬度,則會出現水平滑動條。作爲替代方案,LinearLayout中的按鈕可能會出現「換行符」。

我試過不同的設置,包括listview周圍的滾動視圖,但我從來沒有看到一個滾動條。

所以也許我的問題是LinearLayout不能正確調整大小?每次添加視圖後,我必須做什麼才能使LinearLayout重新計算寬度? invalidate()根本沒有效果。

感謝您的任何幫助。

回答

1

嘗試在horiztonalscrollview中放置linearlayout。一旦按鈕超過屏幕寬度,應該提供滾動條。

+0

嗨,非常感謝。這就是我需要做的。使用horizo​​ntalscrollview而不是滾動視圖。現在它工作! – homtg 2012-01-10 14:36:27

1

嘗試HorizontalScrollView並添加按鈕。這將在需要時自動滾動。如需更多幫助,共享完整的佈局代碼

1

LinearLayout提供的意見只是「線性」的定位;)我的意思是,你可以這樣做:

[btn1][btn2][btn3][btn4] 

或像這樣:

[btn1] 
[btn2] 
[btn3] 
[btn4] 

的區別兩個變體是在android:orientation參數。對於更復雜的視圖,您應該使用TableLayoutRelativeLayout

如果你想要做的線性佈局克里特這種結構的滾動變種:

<HorizontalScrollView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    ...any other params...> 
    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horisontal" 
     ...any other params.../> 
</HorizontalScrollView> 

,並添加按鈕佈局線性像你現在就做。

相關問題