Mint Mint - 2 months ago 12
Android Question

Android : Set gravity of a LinearLayout programmatically

I'm new in android programming.

I just discover that the xml is not the only way to set a layout. So, I'm trying to understand the programmatically set layout. I've been trying to change the position of the button. How can I set the layout gravity so that the button will be positioned in intended axes, let say

bottom
and
center
?

Btw, is the
icicle
same thing as
savedInstanceState
?

Here's the coding that I stumbled upon. Can you please show me the right way to set the gravity?

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

LinearLayout one = new LinearLayout(this);
myButton1 = new Button1(this);
one.addView(myButton1,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
myButton2 = new Button2(this);
one.addView(mButton2,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(one);

Answer

I think, you are looking for

LinearLayout one = new LinearLayout(this);

        one.setGravity(Gravity.BOTTOM | Gravity.CENTER);  //to show LinearLayout gravity

        Button myButton1 = new Button(this);
        one.addView(myButton1,
                    new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        0));
        myButton1.setText("First");
        myButton1.setGravity(Gravity.CENTER);   //to show text gravity in button

        Button myButton2 = new Button(this);
        one.addView(myButton2,
                    new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        0));
        myButton2.setText("Second");
        myButton2.setGravity(Gravity.CENTER);   //to show text gravity
        setContentView(one);

icicle is sometimes used as the name of the parameter.It's just a placeholder for one of the formal parameters onCreate takes one Bundle parameter. It's up to you what to call it.

Some properties of LinearLayout http://stackoverflow.com/a/19065951/2826147