Beppe Beppe - 5 months ago 27
Android Question

How to set Dynamic width and height for an inflated view(button)

I've an activity and I can to create some button programmatically on it with LayoutInflater, like this:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Button newButton = (Button) inflater.inflate(R.layout.my_button, currentTableRow, false);


and my_button.xml:

<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/newButton"
android:layout_width="30dp"
android:layout_height="30dp"</Button>


it works fine. But my question is that: Is there any way that I pass the width and height to my_button.xml or any way that when I want to inflate that view, set the width and height. I mean that sometime I want to set "30dp", sometimes set it to "45dp" etc.Thanks in advance.

Answer

You can try this

newButton .setLayoutParams (new LayoutParams(45, LayoutParams.WRAP_CONTENT)

where LayoutParams(int width, int height)

means first argument is width and second argument is height ..