Android: Center Buttons horiz. and vert. in a ViewGroup
I want to center a group of buttons horizontally and vertically on the display.
This is what I have now:
A Custom RelativeLayout:
RelativeLayout xml_layout = (RelativeLayout) findViewById(R.id.custom_layout_id);
I create programmatically buttons and add them to the xml_layout:
xml_layout.addView(ib[i], lp);
I think I have to use a ViewGroup instead, then add my buttons to the ViewGroup, add rules to center the ViewGroup and then add the ViewGroup to my RelativeLayout.
I tried this
ViewGroup vg;
vg.addView(ib[i], lp); //The local variable vg may not have been initialized
and this
ViewGroup vg = null;
vg.addView(ib[i], lp); //Runtime Error
But it don't work.
I new the theory:
- Create a ViewGroup
- Add my Buttons to the ViewGroup
- Add the ViewGroup to the RelativeLayout
- Add rules to t开发者_如何转开发he ViewGroup to center it horizontally and vertically relative to the RelativeLayout (variable lp)
But don't know the practice. Can someone help me?
Perhaps this gives you the idea:
<?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>
If you want the buttons as a group to be centered, you need to add them to a LinearLayout, instead of a RelativeLayout. Then you can use the same layout params for each of them (WRAP_CONTENT/WRAP_CONTENT), and they won't stack on top of each other and obscure each other.
For your LinearLayout, give it LayoutParams with FILL_PARENT for width and height.
Whenever you use LayoutParams, I recommend you always specify which kind of LayoutParams, to avoid class cast problems, which may be what's happening to you. For example, the layout params for each of your buttons should be LinearLayout.LayoutParams, and the parms for your LinearLayout should be ViewGroup.LayoutParams.
Finally, have you already called setContentView()? Does that view already have your RelativeLayout in it with the id custom_layout_id?
ViewGroup vg = null
is not enough, since you try to dereference a null in the next line: vg.addView(ib[i], lp);
. Instead, create the ViewGroup with one of its constructors. The simplest approach is to do ViewGroup vg = new ViewGroup(this);
.
精彩评论