2012-01-10 88 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> 

,并添加按钮布局线性像你现在就做。

相关问题