Irvin Bridge Irvin Bridge - 2 months ago 8
Android Question

Adding Button to LinearLayout programmatically doesn't work properly

I have a multiple dimens.xml files for all "smallest width" that I use for button size. And also I have multiple versions for main layout and for button layout (for multi-screen support).

I want to insert multiple buttons into layout programmatically and inflate this button with layout from xml.

This is how I do this:

Button temp_button = null;
final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

for(int i = 0; i < 7; i++) {
temp_button = (Button)inflater.inflate(R.layout.answer_letter_button, null);
temp_button.setTextColor(accent_color);

answer_letters.add(temp_button);

answer_panel.addView(answer_letters.get(i));
}


This is a parent layout for these buttons:

<LinearLayout
android:id="@+id/answer_panel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
app:layout_constraintBottom_toTopOf="@+id/letter_panel">
</LinearLayout>


And button layout:

<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="@dimen/answer_letter_button_size"
android:layout_height="@dimen/answer_letter_button_size"
android:text="M"
android:textStyle="bold"
android:textColor="@color/colorAccent"
android:textSize="@dimen/answer_letter_button_text_size"
android:layout_margin="@dimen/answer_letter_button_margin_size"
android:background="@drawable/shaped_button" />


What I want to see:
enter image description here

What I actually see:

enter image description here

What am I doing wrong, somebody tell me?

Sorry, I incorrectly expressed.
I mean, that something is wrong with the size of the resulting button. Mostly with a width of a button.

Answer

You must add layout_weight param and set it to 1 also change layout_width and layout_height to wrap_content, you can'y add 7 items and set height and width from dimens. Your way will be always wrong and result also. Set only textSize from dimens and it be look what you search for.

 <Button
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="M"
        android:textStyle="bold"
        android:textColor="@color/colorAccent"
        android:textSize="@dimen/answer_letter_button_text_size"
        android:layout_margin="@dimen/answer_letter_button_margin_size"
        android:background="@drawable/shaped_button" />

And add in your parent layout, android:weightSum="7".