2011-12-12 79 views
4

是否可以根据屏幕分辨率动态调整文本视图中的字体大小?如果是的话如何?我正在从一个mdpi avd开发。但是,当应用程序安装在hdpi文本显示太小。动态调整文本视图的字体大小

+1

有一个尺寸单位不仅考虑了屏幕分辨率和密度,它还考虑到了用户的字体大小偏好。所以你不必首先进行任何计算。如果你做了一个简短的搜索*(你在问之前应该做的任何事)*你会发现它。 ;) – 2011-12-12 17:32:34

+1

感谢您的评论。我在这里找不到任何相关的问题。这就是为什么我问。 –

回答

3

使用textSize并且缩放像素sp单位是alextsc暗示的。

如果你真的想成为引人入胜的字体,并尽可能大地填充字体来填充宽度,那么使用textWatcher渲染文本并检查大小,然后动态调整字体是可能的。

以下是相当具体的,因为我有一个线性布局中的多个文本视图,这只能调整文本更小,一旦其中一个文本不适合。它会给你一些工作,但。

class LineTextWatcher implements TextWatcher { 

static final String TAG = "IpBike"; 
TextView mTV; 
Paint mPaint; 

public LineTextWatcher(TextView text) { 
    mTV = text; 
    mPaint = new Paint(); 
} 

public void beforeTextChanged(CharSequence s, int start, int count, 
     int after) { 
} 

public void onTextChanged(CharSequence s, int start, int before, int count) { 
} 

public void afterTextChanged(Editable s) { 
    // do the work here. 
    // we are looking for the text not fitting. 
    ViewParent vp = mTV.getParent(); 
    if ((vp != null) && (vp instanceof LinearLayout)) { 
     LinearLayout parent = (LinearLayout) vp; 
     if (parent.getVisibility() == View.VISIBLE) { 
      mPaint.setTextSize(mTV.getTextSize()); 
      final float size = mPaint.measureText(s.toString()); 
      if ((int) size > mTV.getWidth()) { 
       float ts = mTV.getTextSize(); 
       Log.w(TAG, "Text ellipsized TextSize was: " + ts); 
       for (int i = 0; i < parent.getChildCount(); i++) { 
        View child = parent.getChildAt(i); 
        if ((child != null) && (child instanceof TextView)) { 
         TextView tv = (TextView) child; 
         // first off we want to keep the verticle 
         // height. 
         tv.setHeight(tv.getHeight()); // freeze the 
                 // height. 

         tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
           tv.getTextSize() - 1); 
        } else { 
         Log.v(TAG, "afterTextChanged Child not textView"); 
        } 
       } 
      } 
     } 
    } else { 
     Log.v(TAG, "afterTextChanged parent not LinearLayout"); 
    } 
} 
}