I have problem with organizing layout in android aplication. I\'m dynamically creating buttons and adding them with this code to my layout:
LayoutInflate
Setting layout_weight
on the buttons themselves will cause the buttons to expand without having space between them. LinearLayout
never adds space between its child views.
You should wrap each one in a FrameLayout
and use layout_gravity="center"
on your buttons, then set layout_weight="1"
on the FrameLayout
.
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<Button android:layout_{width,height}="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
This also worked by embedding the TextView into a LinearLayout (vertical)
text_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView"
android:layout_margin="10dp"
android:textColor="@color/white"/>
</LinearLayout>
This was embedded into another view where the root view is also a LinerLayout. A convoluted workaround...
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);