androidandroid-layoutlayout-inflater

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.


Solution

  • float scale = context.getResources().getDisplayMetrics().density;
    
    button.getLayoutParams().height = 30 * scale;
    button.getLayoutParams().width = 30 * scale;
    

    by using above code one can simply set height and width in "dp".