'Errors that occur when converting dp to px in Android

I'm using this code to change dp to px.

public static int DpToPixel(Context context, int DP) {
    float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DP, context.getResources().getDisplayMetrics());
    return (int) px;
}

Problem

When creating TextView programmatically, set the width and height in pixels, as shown in the line below.

val width = DpToPixel(requireContext(), 96)
val height = DpToPixel(requireContext(), 14)

val textView = TextView(requireContext()).apply {
    layoutParams = ConstraintLayout.LayoutParams(width, height)
}

As a result, I thought that the width of textView would be 96dp and the height would be 14dp.

However, when I actually checked, the height of the textView was set to 13dp.

Qusetion

  1. How can i resolve error occured when converted dp to px?

  2. Is there anyway creating TextView using width and height in DP unit?

Thank you for reading my question.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source