2011-04-09 52 views
1

我想在 显示屏上水平和垂直放置一组按钮 。Android:中心按钮水平。和vert。在ViewGroup中

这是我现在有:

一个自定义的RelativeLayout:

RelativeLayout xml_layout = (RelativeLayout) findViewById(R.id.custom_layout_id); 

创建编程按钮,将它们添加到xml_layout:

 
xml_layout.addView(ib[i], lp); 

我想我必须使用一个ViewGroup,然后将我的按钮 添加到ViewGroup,添加规则以居中ViewGroup ,然后将ViewGroup添加到我的Re lativeLayout。

我想这


ViewGroup vg; 
vg.addView(ib[i], lp); //The local variable vg may not have been initialized 


ViewGroup vg = null; 
vg.addView(ib[i], lp); //Runtime Error 

但它不工作。

我的新理论:

  1. 创建的ViewGroup
  2. 我的按钮添加到一个ViewGroup
  3. 的ViewGroup中添加到RelativeLayout的
  4. 规则添加到一个ViewGroup水平居中它
    并垂直于RelativeLayout(变量lp)

但是不知道这种做法。 有人可以帮我吗?

回答

0

如果您希望按钮作为一个组居中,您需要将它们添加到LinearLayout而不是RelativeLayout。然后你可以为它们中的每一个使用相同的布局参数(WRAP_CONTENT/WRAP_CONTENT),它们不会堆叠在一起并相互混淆。

对于您的LinearLayout,请为其宽度和高度使用FILL_PARENT的LayoutParams。

无论何时您使用LayoutParams,我都建议您始终指定哪种LayoutParams,以避免类转换问题,这可能是您正在发生的事情。例如,每个按钮的布局参数应该是LinearLayout.LayoutParams,而LinearLayout的参数应该是ViewGroup.LayoutParams。

最后,你有没有叫过setContentView()?该视图是否已经在您的RelativeLayout中使用了id custom_layout_id?

1

这或许让你的想法:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:layout_gravity="center" 
    android:weightSum="5"> 
    <Button 
     android:layout_width="0dip" 
     android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:text="ABC" /> 
    <Button 
     android:layout_width="0dip" 
     android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:text="DEFG" /> 
    <Button 
     android:layout_width="0dip" 
     android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:text="HI" /> 
    <Button 
     android:layout_width="0dip" 
     android:layout_height="fill_parent" 
     android:layout_weight="1" 
     android:text="J" /> 
</LinearLayout>

0

ViewGroup vg = null是不够的,因为你尝试取消引用下一行空:vg.addView(ib[i], lp);。相反,使用its constructors之一创建ViewGroup。最简单的方法是做ViewGroup vg = new ViewGroup(this);