Skip to content
Advertisement

Dynamic buttons look different than static buttons

I have a layout problem. In my XML, I have some static buttons:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#00BCD4"
    android:orientation="vertical"
    android:tag="general"
    tools:context=".fragments.GeneralFragment">

    <Button
        android:id="@+id/hello"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center_vertical"
        android:onClick="onClick"
        android:tag="Greeting"
        android:text="@string/hello" />

    <Button
        android:id="@+id/observed"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center_vertical"
        android:onClick="onClick"
        android:text="@string/observed" />
...

So this is a list of buttons and I would like to add some further buttons dynamically. This is how I do it:

LinearLayout layout = view.findViewById(R.id.root);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    for(String text : readFromSharedPreferences(getContext())) {
        Button btn = new Button(this.getContext());
        btn.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        btn.setText(text);
        btn.setTag(text);
        btn.setPadding(30, 0, 0, 0);
        btn.setTextColor(Color.BLACK);
        btn.setBackgroundColor(Color.GRAY);
        layout.addView(btn);

And this is how they look like: enter image description here

I am missing the spaces between the dynamic buttons. It looks like the buttons have been added right AFTER LinearLayout but not into it.

My goal is that they look exactly the same. How can I fix that?

Advertisement

Answer

The layout parameters given to the dynamic are different from the ones set in the XML. There are few options to fix this, either create new LayoutParams with the same values or use the same ones assigned for the statically created buttons in the XML.

For Example:

// Before the foreach loop define a reference for the first button created:
LinearLayout layout = findViewById(R.id.root);
Button b = (Button)layout.getChildAt(0);

// inside your foreach loop ( instead of SharedPref I used an ArrayList)
for (String text : arr) {
        Button btn = new Button(this);
        btn.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
        btn.setText(text);
        btn.setTag(text);
        btn.setLayoutParams(b.getLayoutParams());
        btn.setBackground(b.getBackground());
        layout.addView(btn);
    }

Please note that there is possibly an easier way to get XML element attributes – I am not sure how to retrieve them

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement