Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relation between "dp" and int in Android Studio?

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 ?

like image 595
vainquit Avatar asked Oct 20 '25 21:10

vainquit


1 Answers

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.

like image 121
Tariqul Islam Avatar answered Oct 23 '25 10:10

Tariqul Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!