【问题标题】:How to find the Text Area(Height/Width) of TextView programmatically in android如何在android中以编程方式查找TextView的文本区域(高度/宽度)
【发布时间】:2014-08-13 02:47:32
【问题描述】:

我有一个EditText、一个Button 和一个TextView。单击按钮时,textview 会显示用 edittext 编写的文本。是否可以根据文本找到占用的文本视图的大小。即如果它有三个字符“abc”,那么现在宽度是多少,如果它有五个字符,比如“abcde”,那么宽度是多少?

【问题讨论】:

    标签: android android-layout textview layoutparams


    【解决方案1】:
    Rect bounds = new Rect();
    Paint textPaint = textView.getPaint();
    textPaint.getTextBounds(text,0,text.length(),bounds);
    int height = bounds.height();
    int width = bounds.width();
    

    textView.setText("bla");
    textView.measure(0, 0);
    textView.getMeasuredWidth();
    textView.getMeasuredHeight();
    

    【讨论】:

    • 这很好用 - 直到文本太长而无法放入一行并换行,然后添加第二行。由于 getTextBounds() 不知道一行文本的可用空间,因此计算出的高度将严重低估实际高度。
    【解决方案2】:

    请试试这个:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView edit = (TextView) findViewById(R.id.edit);
        edit.setTextSize(20);       
        edit.setText("Hello, world");       
        edit.measure(0, 0);
        int width = edit.getMeasuredWidth();
        Log.w("width", width.toString());
    }
    

    在获得宽度之前,您必须测量视图/标签/文本编辑。 如果这不起作用,请告诉我。

    【讨论】:

    • 两个答案都是正确的,你的和上面的一个......谢谢它的工作。
    • 请标记为答案(下面的按钮否决投票)我很高兴它奏效了。
    • 这将返回 0,因为尚未绘制视图。它必须在 view.post() 的 Runnable 中完成才能获得尺寸
    【解决方案3】:
    TextView txt = new TextView(mContext);
    txt.setText("Some Text)";
    int height = txt.getLineCount() *  txt.getLineHeight();
    int width = txt.getWidth();
    

    【讨论】:

      【解决方案4】:

      试试这个方法,希望能帮助你解决问题。

      yourTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
         @Override
         public void onGlobalLayout() {
           int width = yourTextView.getMeasuredWidth();
           int height = yourTextView.getMeasuredHeight();
      
         }
      });
      

      【讨论】:

      【解决方案5】:

      请告诉我宽度???你要吗?

      TextView 方法 getWidth() 为您提供视图的宽度,以像素为单位

      TextView textView = (TextView)findViewById(R.id.textview);
      textView.getWidth(); //width of your view, in pixels 
      

      【讨论】:

      • 我的意思是根据文本找到宽度。
      猜你喜欢
      • 2017-02-28
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多