Reputation: 6983
I'm dynamically creating horizontal LinearLayout with 5 views added to each one. It is then added to a vertical LinearLayout that is inside a scroll view.
I set the gravity by layout.setGravity( Gravity.CENTER );, but it is not centred but left algined.
THe code that creates the horizontal LinearLayouts
for(int i=0; i<cGlobals.mNames.length; i+=2)
{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setGravity( Gravity.CENTER );
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(llp);
AddButton( layout, cGlobals.mNames[i], i);
TextView t=new TextView(this);
t.setText(" ");
layout.addView(t);
if (i+1<cGlobals.mNames.length)
AddButton( layout, cGlobals.mNames[i+1], i+1);
Container.addView(layout);
}
code that creats the buttons added to the linar layout
void AddButton( LinearLayout layout, String name, int i)
{
favBut[i]=new ImageView(this);
if ( cGlobals.conFav.contains( name ) )
favBut[i].setImageResource(R.drawable.heartselected2);
else
favBut[i].setImageResource(R.drawable.heartunselected2);
favBut[i].setId(defStartFavId+i);
favBut[i].setOnClickListener(this);
layout.addView(favBut[i]);
int w=getWindowManager().getDefaultDisplay().getWidth();
w-=200; // hearts
w=w/2;
Button but1=new Button(this);
but1.setText( name);
but1.setWidth(w);
layout.addView(but1);
but1.setOnClickListener(this);
but1.setId(defStartButId+i);
}
XML file for layout
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal" >
<Button
android:id="@+id/butVol"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:textSize="24px"
android:text="Volume"
android:textColor="#ff0000ff"
android:layout_gravity="center"
/>
<Button
android:id="@+id/butRington"
android:layout_width="140dp"
android:layout_height="wrap_content"
android:textSize="24px"
android:text="Rington"
android:textColor="#ff0000ff"
android:layout_gravity="center"
/>
Upvotes: 0
Views: 1647
Reputation: 2332
You can try to specify layout parameters like this...
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
layout.addView(favBut[i], layoutParams);
and/or
Container.addView(layout, layoutParams);
and maybe change MATCH_PARENT to WRAP_CONTENT depdning on the results you are after.
http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html
Upvotes: 2