How can I set a minimum width (in characters) for a TextView?

前端 未结 5 1527
无人共我
无人共我 2020-12-28 14:42

I\'ve had a good search for this on here and can\'t find a solution.

I have a TextView in a RelativeLayout which contains an integer number. The number will range be

相关标签:
5条回答
  • 2020-12-28 14:49

    I think you're looking for the getTextBounds() method in the Paint class. Didn't try it myself tho.

    0 讨论(0)
  • 2020-12-28 14:57

    Use android:maxLength attribute of TextView.Please read this

    0 讨论(0)
  • 2020-12-28 14:58

    try this:

    android:layout_width="wrap_content"
    android:minEms="2"
    
    0 讨论(0)
  • 2020-12-28 15:04

    Ems works if your font is monospace. For proportional fonts, you want it the width of two '0's, not two 'm's. You can fall back to TextPaint.measureText like so:

    float measureText = zip.getPaint().measureText("00000");
    zip.setWidth(zip.getPaddingLeft() + zip.getPaddingRight() + (int) measureText);
    
    0 讨论(0)
  • 2020-12-28 15:09

    Best way is to use TextPaint. Here is a simple example:

    TextPaint textPaint = new TextPaint();
    textPaint.setTextSize(yourTextView.getTextSize());
    yourTextView.setMinWidth((int) textPaint.measureText("-88.88"));
    

    Do not forget to specify text size in your TextPaint object
    In measureText enter longest possible string you're expecting to see (I've written "-88.88" assuming my text can handle positive or negative numbers below 100 with 2 digits after comma)

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