Reputation: 201
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.
Upvotes: 1
Views: 2783
Reputation: 4651
In Kotlin you can do like this:
val scale=this.resources.displayMetrics.density
btn.layoutParams.width=(40 * scale).toInt()
btn.layoutParams.height=(40 * scale).toInt()
where height and width must be integer number
Upvotes: 0
Reputation: 176
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".
Upvotes: 3
Reputation: 27529
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 ..
Upvotes: 2