We all know that a TextView has an attribute "textSize", whose unit varies from "dp" to "sp".
But one day when I am searching a question "Set ImageView width and height programmatically", I find the highest voted answer wrote: image_view.getLayoutParams().height = 20;
Actually I want to programmingly set an ImageView's height as tall as a TextView, but the textSize of the TextView is 20dp, and the height of the ImageView is an int, 20.
So what is the relation between "dp" and "int" ? How can I convert one to another ?
By programmatically when you set view's width, the height it actually takes pixel as an integer value. So when you set image_view.getLayoutParams().height = 20; that means it takes 20 pixel. But you can also set dp in width and height by converting dp to pixel . You can convert by this
final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);
Here dps your actual dp and its converting pixel for setting width and height.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With