3

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 ?

VikaS GuttE
  • 1,636
  • 2
  • 14
  • 38
vainquit
  • 491
  • 6
  • 13

1 Answers1

3

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.

Tariqul Islam
  • 680
  • 6
  • 14
  • That's clear! But I have one more question: why you "+0.5f" at last? – vainquit Jan 04 '20 at 09:05
  • It is actually a formula to convert dp to the pixel. And I can say that the +0.5f, the purpose is to round to the nearest pixel. For more information, you can visit https://developer.android.com/training/multiscreen/screendensities – Tariqul Islam Jan 04 '20 at 09:14
  • Well, that's a bit complicated to me, and maybe I need more time to understand them and ask another question some other days. But I do figure out the answer of the original question, so thank you very much! – vainquit Jan 04 '20 at 09:21