Invader Zim
Invader Zim

Reputation: 838

Inflated button has wrong width and height

I'm building a navigation fragment. There is a button which is always present (main button) and others which are dynamically added and removed.

I have a xml resource file from which I inflate a button, change it's icon and add it to the fragments root layout.

Almost everything works, except for the button size. Button size after is 0 (getWidth()/getHeight()).

button_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/navigation_button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/icon_test"
    android:backgroundTint="@drawable/selector_bar_button"></Button>

inflating code

Button butt = (Button) inflater.inflate(R.layout.button_navigation, null, false);

buttons.add(butt);
root_view.addView(butt);

creating inflater

public void setParent(MainActivity activity){
        parent = activity;
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

variables

MainActivity parent;
LayoutInflater inflater;

int index;

ArrayList<Button> buttons;
Button button_main;
LinearLayout root_view;

Main button, has the exact code as button_navigation.xml and occurs in the layout file of the fragment. The main button's size is good.

Upvotes: 1

Views: 928

Answers (2)

SpiritCrusher
SpiritCrusher

Reputation: 21053

Wrap your button inside a layout.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<Button
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/nickname_message"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:text="adawd awdaw"
    android:textSize="18sp"
    android:textStyle="bold" />

Then add it at runtime.

linearLayout.addView(LayoutInflater.from(this).inflate(R.layout.item_layout,null));

Upvotes: 5

Sayok Majumder
Sayok Majumder

Reputation: 1091

Try using this in your java code button.setLayoutParams (new LayoutParams(60,60);

Upvotes: 0

Related Questions