【问题标题】:TextView text shrink to the given widthTextView 文本缩小到给定的宽度
【发布时间】:2011-05-04 19:35:28
【问题描述】:

我的活动中有一个 textview 字段。它的字体大小为 16。 它的文本是通过代码设置的。假设如果我有一个大文本,它应该缩小这个数据(即字体大小减小)而不是转到下一行。我该怎么做?

<TextView android:id="@+id/textView" android:layout_width="400dp" android:layout_height="wrap_content" android:text="" android:textSize="16sp" />

【问题讨论】:

    标签: android textview


    【解决方案1】:

    我通过使用我根据我的要求创建的以下方法得到它。

    private void autoScaleTextViewTextToHeight(TextView tv)
        {
            String s = tv.getText().toString();
            float currentWidth = tv.getPaint().measureText(s);
    
            float phoneDensity = this.getResources().getDisplayMetrics().density;
    
            while(currentWidth > (REQUIRED_WIDTH * phoneDensity)) {         
                tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, tv.getTextSize() - 1.0f); 
                currentWidth = tv.getPaint().measureText(s);
            }
        }
    

    【讨论】:

      【解决方案2】:

      以下方法以TextView为参数,根据给定TextView的宽度调整其字体大小

      private void adjustTextSize(TextView tv) {
      
          float size = tv.getPaint().getTextSize();
          TextPaint textPaint = tv.getPaint();
          float stringWidth = textPaint.measureText(tv.getText().toString());
          int textViewWidth = tv.getWidth();
          if(textViewWidth > stringWidth) {
      
              float percent = (textViewWidth / stringWidth);
              textPaint.setTextSize(size*percent);
          }
      }
      

      希望这会有所帮助。

      【讨论】:

        【解决方案3】:

        没有什么好办法。您可以做的是计算您将要放置在此 TextView 中的文本的大小,并重新调整您的字体大小,直到它适合目标区域。计算大小使用 Paint.getTextBounds()。

        我在画布上绘图的方法非常相似。需要一个循环来减小字体大小,直到计算后的大小合适。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-04-20
          • 2021-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多