动态调整textview的字体大小

时间:2011-12-12 17:28:51

标签: android

是否可以根据屏幕分辨率动态调整textview中的字体大小?如果有,怎么样?我正在开发一个mdpi avd。但是当应用程序安装在hdpi上时,文本显得太小了。

1 个答案:

答案 0 :(得分: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");
    }
}
}
相关问题