Setting textSize in custom view results in huge text

前端 未结 2 1203
挽巷
挽巷 2021-02-02 06:07

I\'m calling the following in the constructor of my custom view:

private void style(Resources.Theme theme, AttributeSet attrs) {
    TypedArray a = theme.obtainS         


        
2条回答
  •  时光说笑
    2021-02-02 06:48

    @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);
    }
    

提交回复
热议问题