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.
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 ..
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".
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.