How do I set Layout and Text size to DP inside program?

后端 未结 3 1253
长情又很酷
长情又很酷 2021-01-31 15:02

Basically I have this inside XML, but I have to recreate it inside a code. How do I do it?



        
相关标签:
3条回答
  • 2021-01-31 15:43

    Solved here.

    Extract:

    DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
    float dp = 20f;
    float fpixels = metrics.density * dp;
    int pixels = (int) (fpixels + 0.5f);
    
    0 讨论(0)
  • 2021-01-31 15:58

    Just for completeness: Another solution (which I'd prefer) for the question is given here

    setTextSize(float) expects a scaled pixel value. So, setTextSize(10) would give you the desired result. However, getDimension() and getDimensionPixelSize() return the size in units of pixels.

    So for your example it would be

    setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.edTxt_text_size));
    

    where <dimen name="edtxt_text_size">10dp</dimen> is set in your dimens.xml file for example.

    0 讨论(0)
  • 2021-01-31 16:02

    You can use:

    float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
    

    Now the value of pixels is equivalent to 10dp at the device's current screen density.

    The TypedValue contains other similar methods that help in conversion.

    0 讨论(0)
提交回复
热议问题