Setting textSize in custom view results in huge text

Solution 1:

Try the following instead:

line1Size = a.getDimensionPixelSize(R.styleable.StackedTextView_line1_textSize, 0);
line2Size = a.getDimensionPixelSize(R.styleable.StackedTextView_line2_textSize, 0);

if (line1Size > 0) {
    holdr.textLine1.setTextSize(TypedValue.COMPLEX_UNIT_PX, line1Size);
}
if (line2Size > 0) {
    holdr.textLine2.setTextSize(TypedValue.COMPLEX_UNIT_PX, line2Size);
}

Solution 2:

@loeschg I had the same problem, but I finally managed to solve using @plackemacher 's reply more that link

Method .getDimensionPixelSizealways() returns the value in pixel, so you have to use convertPixelsToDp method to get the dp value.

Here is the code that can help you:

 /**
 * This method converts device specific pixels to density independent pixels.
 * 
 * @param px A value in px (pixels) unit. Which we need to convert into db
 * @param context Context to get resources and device specific display metrics
 * @return A float value to represent dp equivalent to px value
 */
public static float convertPixelsToDp(float px, Context context){
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}

line1Size = convertPixelsToDp(a.getDimensionPixelSize(R.styleable.StackedTextView_line1_textSize, 0), some_context);
line2Size = convertPixelsToDp(a.getDimensionPixelSize(R.styleable.StackedTextView_line2_textSize, 0), some_context);

if (line1Size > 0) {
    holdr.textLine1.setTextSize(TypedValue.COMPLEX_UNIT_PX, line1Size);
}
if (line2Size > 0) {
    holdr.textLine2.setTextSize(TypedValue.COMPLEX_UNIT_PX, line2Size);
}