欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android编程实现自动调整TextView字体大小以适应文字长度的方法

程序员文章站 2023-12-19 17:08:22
本文实例讲述了android编程实现自动调整textview字体大小以适应文字长度的方法。分享给大家供大家参考,具体如下: package com.test.an...

本文实例讲述了android编程实现自动调整textview字体大小以适应文字长度的方法。分享给大家供大家参考,具体如下:

package com.test.android.textview;
import android.content.context;
import android.graphics.paint;
import android.util.attributeset;
import android.widget.textview;
public class customtextview extends textview {
  private static float default_min_text_size = 10;
  private static float default_max_text_size = 20;
  // attributes
  private paint testpaint;
  private float mintextsize;
  private float maxtextsize;
  public customtextview(context context, attributeset attrs) {
    super(context, attrs);
    initialise();
  }
  private void initialise() {
    testpaint = new paint();
    testpaint.set(this.getpaint());
    // max size defaults to the intially specified text size unless it is
    // too small
    maxtextsize = this.gettextsize();
    if (maxtextsize <= default_min_text_size) {
      maxtextsize = default_max_text_size;
    }
    mintextsize = default_min_text_size;
  }
  /**
  * re size the font so the specified text fits in the text box * assuming
  * the text box is the specified width.
  */
  private void refittext(string text, int textwidth) {
    if (textwidth > 0) {
      int availablewidth = textwidth - this.getpaddingleft() -
        this.getpaddingright();
      float trysize = maxtextsize;
      testpaint.settextsize(trysize);
      while ((trysize > mintextsize) &&
          (testpaint.measuretext(text) > availablewidth)) {
        trysize -= 1;
        if (trysize <= mintextsize) {
          trysize = mintextsize;
          break;
        }
        testpaint.settextsize(trysize);
      }
      this.settextsize(trysize);
    }
  }
  @override
  protected void ontextchanged(charsequence text, int start, int before,
    int after) {
    super.ontextchanged(text, start, before, after);
    refittext(text.tostring(), this.getwidth());
  }
  @override
  protected void onsizechanged(int w, int h, int oldw, int oldh) {
    if (w != oldw) {
      refittext(this.gettext().tostring(), w);
    }
  }
}

希望本文所述对大家android程序设计有所帮助。

上一篇:

下一篇: