I have problem with organizing layout in android aplication. I'm dynamically creating buttons and adding them with this code to my layout:
LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < NO_NUMBERS; i++){
Button btn = new Button(this);
btn = (Button) layoutInflater.inflate(R.layout.button, null);
btn.setId(2000+i);
Integer randomNumber = sort.getNumbersCopy()[i];
btn.setText(randomNumber.toString());
btn.setOnClickListener((OnClickListener) this);
buttonList.addView(btn);
list.add(btn);
}
I'm adding it to the LinearLayout:
<LinearLayout
android:id="@+id/buttonlist"
android:layout_alignParentLeft="true"
android:layout_marginTop="185dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:orientation="horizontal"
android:gravity="center_horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>
and i'm importing this .xml where i'm defining button layout:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:textSize="26dp"
android:textStyle ="bold"
android:textColor="#ffffff"
android:background="@drawable/button"
android:layout_marginLeft="8px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
Well, layout always ends up like this:
Instead of something like this (even spce between buttons, square buttons):
To summarize this: I have to:
On a LinearLayout, place it at the bottom and make sure to set the elements layout_weight properly. Show activity on this post. Set android:layout_gravity="bottom" . Hope this helps.
You can set the android:layout_weight='1' and both buttons will share the screen equally(side by side) or if you want the extra space between them, you can place a button each in a linear layout and set the android:layout_gravity to left and right for each.
android:layout_margin. Specifies extra space on the left, top, right and bottom sides of this view.
Remember, android:layout_*
attributes are LayoutParams
. They are arguments to the parent and affect how the parent will perform layout on that view. You're specifying layout_margin
attributes on your buttons, but they're getting ignored. Here's why:
Since LayoutParams
are specific to the parent view type, you need to supply an instance of the correct parent type when you inflate layouts using a LayoutInflater
or else layout_
attributes on the top-level view in the layout will be dropped. (The inflater would have no idea what type of LayoutParams
to generate.)
Since buttonList
is your intended parent for the button views, change your inflate
line to this:
btn = (Button) layoutInflater.inflate(R.layout.button, buttonList, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With