How to assign text size in sp value using java code

后端 未结 11 1929
無奈伤痛
無奈伤痛 2020-12-04 05:14

If I assign an integer value to change a certain text size of a TextView using java code, the value is interpreted as pixel (px).

Now does

相关标签:
11条回答
  • 2020-12-04 05:48

    Based on the the source code of setTextSize:

    public void setTextSize(int unit, float size) {
        Context c = getContext();
        Resources r;
    
        if (c == null)
            r = Resources.getSystem();
        else
            r = c.getResources();
    
        setRawTextSize(TypedValue.applyDimension(
            unit, size, r.getDisplayMetrics()));
    }
    

    I build this function for calulating any demension to pixels:

    int getPixels(int unit, float size) {
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        return (int)TypedValue.applyDimension(unit, size, metrics);
    }
    

    Where unit is something like TypedValue.COMPLEX_UNIT_SP.

    0 讨论(0)
  • 2020-12-04 05:51

    Thanks @John Leehey and @PeterH:

    desiredSp = getResources().getDimension(R.dimen.desired_sp);
    density = getResources().getDisplayMetrics().density;
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, desiredSp / density);
    

    The thing is if you define R.dimen.desired_sp to 25 in your dimen.xml

    1. On non-HD Device: desiredSp is still 25, density = 1
    2. On HD Device(like Nexus 7 2nd Generation): desiredSp becomes 50 ish, density = 2
    0 讨论(0)
  • 2020-12-04 05:52
    semeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
                           context.getResources().getDimension(R.dimen.text_size_in_dp))
    
    0 讨论(0)
  • 2020-12-04 05:58

    From Api level 1, you can use the public void setTextSize (float size) method.

    From the documentation:

    Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.

    Parameters: size -> float: The scaled pixel size.

    So you can simple do:

    textView.setTextSize(12); // your size in sp
    
    0 讨论(0)
  • 2020-12-04 05:59

    When the accepted answer doesn't work (for example when dealing with Paint) you can use:

    float spTextSize = 12;
    float textSize = spTextSize * getResources().getDisplayMetrics().scaledDensity;
    textPaint.setTextSize(textSize);
    
    0 讨论(0)
  • 2020-12-04 06:02

    After trying all the solutions and none giving acceptable results (maybe because I was working on a device with default very large fonts), the following worked for me (COMPLEX_UNIT_DIP = Device Independent Pixels):

    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    
    0 讨论(0)
提交回复
热议问题