androidxmldensity-independent-pixel

Dp in xml doesn't match java dp-px conversion


I need to set sizes of text, margins or images in java rather than in xml due to loop repetition.

When I set 20dp for text in xml file, result is 3x smaller than same 20dp converted to px with this (Material design guide based) conversion method:

dp = (width in pixels * 160) / density

How to get same dp across xml and java?

res:

<resources>

    <dimen name="cat_height">20dp</dimen>

</resources>

xml:

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Business"
            android:textSize="@dimen/cat_height"
            android:textStyle="bold" />

Java:

int dp20 = getResources().getDimensionPixelSize(R.dimen.cat_height);

(...)

TextView categoryText = new TextView(this);                                                                                                      
categoryText.setText(subCategoryNames.get(i));                                                                                                   
categoryText.setTextSize(dp20);                                                                                                                  
categoryText.setTypeface(null, Typeface.BOLD);                                                                                                   
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(dp20, dp20, dp20, dp20);                                                                                                       
mainLinear.addView(categoryText, params);                                                                                                        

above xml, below java result

Thanks in advance!


Solution

  • use this

    categoryText.setTextSize(TypedValue.COMPLEX_UNIT_PX,dp20);