Android中计算textsvg text 文字大小小的几个方法

Android编程实现自动调整TextView字体大小以适应文字长度的方法
转载 &发布时间:日 09:29:45 & 作者:hshm20517
这篇文章主要介绍了Android编程实现自动调整TextView字体大小以适应文字长度的方法,涉及Android基于TextView类的继承及Paint属性操作实现字体大小自适应的相关技巧,需要的朋友可以参考下
本文实例讲述了Android编程实现自动调整TextView字体大小以适应文字长度的方法。分享给大家供大家参考,具体如下:
package com.test.android.
import android.content.C
import android.graphics.P
import android.util.AttributeS
import android.widget.TextV
public class CustomTextView extends TextView {
private static float DEFAULT_MIN_TEXT_SIZE = 10;
private static float DEFAULT_MAX_TEXT_SIZE = 20;
// Attributes
private Paint testP
private float minTextS
private float maxTextS
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 = maxTextS
testPaint.setTextSize(trySize);
while ((trySize & minTextSize) &&
(testPaint.measureText(text) & availableWidth)) {
trySize -= 1;
if (trySize &= minTextSize) {
trySize = minTextS
testPaint.setTextSize(trySize);
this.setTextSize(trySize);
protected void onTextChanged(CharSequence text, int start, int before,
int after) {
super.onTextChanged(text, start, before, after);
refitText(text.toString(), this.getWidth());
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w);
希望本文所述对大家Android程序设计有所帮助。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具博客分类:
手机设备太多,分辨率也不一样,看到网上大部分的适应字体的方法是定义values320×480或value-hdpi方式去处理。
采用第一种的就惨了,很多设备的分辨率是不一样的,难道要每种都定义吗?
采用第二种的在平板电脑里没有效果。
最后还是代码的方式方便快捷。。。
//遍历设置字体
public static void changeViewSize(ViewGroup viewGroup,int screenWidth,int screenHeight) {//传入Activity顶层Layout,屏幕宽,屏幕高
int adjustFontSize = adjustFontSize(screenWidth,screenHeight);
for(int i = 0; i&viewGroup.getChildCount(); i++ ){
View v = viewGroup.getChildAt(i);
if(v instanceof ViewGroup){
changeViewSize((ViewGroup)v,screenWidth,screenHeight);
}else if(v instanceof Button){//按钮加大这个一定要放在TextView上面,因为Button也继承了TextView
( (Button)v ).setTextSize(adjustFontSize+2);
}else if(v instanceof TextView){
if(v.getId()== R.id.title_msg){//顶部标题
( (TextView)v ).setTextSize(adjustFontSize+4);
( (TextView)v ).setTextSize(adjustFontSize);
//获取字体大小
public static int adjustFontSize(int screenWidth, int screenHeight) {
screenWidth=screenWidth&screenHeight?screenWidth:screenH
* 1. 在视图的 onsizechanged里获取视图宽度,一般情况下默认宽度是320,所以计算一个缩放比率
rate = (float) w/320
w是实际宽度
2.然后在设置字体尺寸时 paint.setTextSize((int)(8*rate));
8是在分辨率宽为320 下需要设置的字体大小
实际字体大小 = 默认字体大小 x
int rate = (int)(5*(float) screenWidth/320); //我自己测试这个倍数比较适合,当然你可以测试后再修改
return rate&15?15: //字体太小也不好看的
最后在Avtivity的oncreate完后调用一下changeViewSize就行了。。。文字大了那么它对应的背景也就跟着大,所以建议控件的背景图片用9宫格类型的图片,看起来舒服。
另外附加,如果你开发的应用想在平板电脑上浏览无碍请在AndroidManifest.xml文件中的manifest节点(DTD建议放在application节点上面)里加入:
&supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:resizeable="true"/&
浏览 22345
浏览: 31621 次
来自: 广州
不错,正合吾意~~
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'扫一扫体验手机阅读
Android中计算textView长度问题
<span type="1" blog_id="984775" userid='
分享到朋友圈
关注作者,不错过每一篇精彩[转]Android中的一个TextView中的字体设置不同大小 - freeliver54 - 博客园
随笔 - 2615, 文章 - 3, 评论 - 2400, 引用 - 157
本文转自:
如图,这个是桌面Widget中的截图,最好是通过一个TextView实现,这是我提出的问题,近几天解决。呵呵,当然写两个TextView很简单也很容易设置。
Java代码 &
title.setText("Your&big&island&&b&ADVENTURE!&/b&");&&title.setText("Your big island &b&ADVENTURE!&/b&");//这是原样显示,我想让加粗
还有,我想能不能类似的给上边那样通过html标签设置样式。网上搜过,果然可以。
Java代码 &
{ &&&&&final&SpannableStringBuilder&sb&=&new&SpannableStringBuilder("your&text&here"); &&&&&final&ForegroundColorSpan&fcs&=&new&ForegroundColorSpan(Color.rgb(<font color="#c0,&<font color="#c0,&<font color="#c0));&&&&&&final&StyleSpan&bss&=&new&StyleSpan(android.graphics.Typeface.BOLD);&&&&&&sb.setSpan(fcs,&0,&4,&Spannable.SPAN_INCLUSIVE_INCLUSIVE);&&&&&&sb.setSpan(bss,&0,&4,&Spannable.SPAN_INCLUSIVE_INCLUSIVE);&&&&&&yourTextView.setText(sb); &&}&&{
final SpannableStringBuilder sb = new SpannableStringBuilder("your text here");
final ForegroundColorSpan fcs = new ForegroundColorSpan(Color.rgb(158, 158, 158)); // Span to set text color to some RGB value
final StyleSpan bss = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold
sb.setSpan(fcs, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // Set the text color for first 4 characters
sb.setSpan(bss, 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make them also bold
yourTextView.setText(sb);
另外android帮我们封装了简单的方法。
Java代码 &
title.setText(Html.fromHtml("Your&big&island&&b&ADVENTURE!&/b&"));&&&title.setText(Html.fromHtml("Your big island &b&ADVENTURE!&/b&"));
但是,我通过这个方法,在widget中设置,不太可行。又是个疑问了,但到在widget中通过html代码设置字体大小不行么?
如果你经常的使用设置TextView中的字体,最好使用Spannable或SpannableBuilder之类的。网上说Html.fromHtml不是很高效,因为这是通过一个很大的xml来解析的。
我再试试Spannable
Java代码 &
TextView&TV&=&(TextView)findViewById(R.id.mytextview01);& &&Spannable&WordtoSpan&=&new&SpannableString("I&know&just&how&to&whisper,&And&I&know&just&how&to&cry,I&know&just&where&to&find&the&answers");&&&&&&&& &&WordtoSpan.setSpan(new&ForegroundColorSpan(Color.BLUE),&15,&30,&Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); &&TV.setText(WordtoSpan);&&TextView TV = (TextView)findViewById(R.id.mytextview01);
Spannable WordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(WordtoSpan);
经过测试通过这种方法还是不能够改变widget中的字体大小。
Java代码 &
Spannable&WordtoSpan&=&new&SpannableString("大字小字"); &&WordtoSpan.setSpan(new&AbsoluteSizeSpan(11),&0,&1,&Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); &&WordtoSpan.setSpan(new&AbsoluteSizeSpan(21),&2,&3,&Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); &&remoteViews.setCharSequence(R.id.text11,&"setText",&WordtoSpan.toString()); &&ComponentName&com&=&new&ComponentName("com.jftt.widget",&"com.jftt.widget.MyWidgetProvider"); &&appWidgetManager.updateAppWidget(com,&remoteViews);&&Spannable WordtoSpan = new SpannableString("大字小字");
WordtoSpan.setSpan(new AbsoluteSizeSpan(11), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
WordtoSpan.setSpan(new AbsoluteSizeSpan(21), 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
remoteViews.setCharSequence(R.id.text11, "setText", WordtoSpan.toString());
ComponentName com = new ComponentName("com.jftt.widget", "com.jftt.widget.MyWidgetProvider");
appWidgetManager.updateAppWidget(com, remoteViews);
经过我的修改终于成功了,原来试试自己使用错误啊。下边是正确代码。
Java代码 &
Spannable&WordtoSpan&=&new&SpannableString("大字小字"); &&WordtoSpan.setSpan(new&AbsoluteSizeSpan(20),&0,&2,&Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); &&WordtoSpan.setSpan(new&AbsoluteSizeSpan(14),&2,&4,&Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); &&remoteViews.setCharSequence(R.id.text11,&"setText",&WordtoSpan); &&ComponentName&com&=&new&ComponentName("com.jftt.widget",&"com.jftt.widget.MyWidgetProvider"); &&appWidgetManager.updateAppWidget(com,&remoteViews);&&Spannable WordtoSpan = new SpannableString("大字小字");
WordtoSpan.setSpan(new AbsoluteSizeSpan(20), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
WordtoSpan.setSpan(new AbsoluteSizeSpan(14), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
remoteViews.setCharSequence(R.id.text11, "setText", WordtoSpan);
ComponentName com = new ComponentName("com.jftt.widget", "com.jftt.widget.MyWidgetProvider");
appWidgetManager.updateAppWidget(com, remoteViews);
相信对比可以看出我错在哪里了吧!是的,我错误的使用了toString方法。
效果如图:textview固定长度,怎么样设置字体大小,让显示的字符串正好占满整个textview?
要求在不同的设备中都可以。
该问题被发起重新开启投票
投票剩余时间:
之前被关闭原因:
该问题被发起删除投票
投票剩余时间:
距离悬赏到期还有:
参与关闭投票者:
关闭原因:
该问题已经被锁定
锁定原因:()
保护原因:避免来自新用户不合宜或无意义的致谢、跟帖答案。
该问题已成功删除,仅对您可见,其他人不能够查看。
我提供一个扩展TestView类,思路是:定义一个最大的文字大小,一个最小的文字大小(可改变),它只是通过它们之间的大小递减运行,直到它找到的最大适合的一个。
import android.content.Cimport android.graphics.Pimport android.util.AttributeSimport android.widget.TextVpublic class FontFitTextView extends TextView {
public FontFitTextView(Context context) {
super(context);
initialise();
public FontFitTextView(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 & 11) {
maxTextSize = 20;
minTextSize = 10;
/* 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 = maxTextS
testPaint.setTextSize(trySize);
while ((trySize & minTextSize) && (testPaint.measureText(text) & availableWidth)) {
trySize -= 1;
if (trySize &= minTextSize) {
trySize = minTextS
testPaint.setTextSize(trySize);
this.setTextSize(trySize);
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
refitText(text.toString(), this.getWidth());
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w);
//Getters and Setters
public float getMinTextSize() {
return minTextS
public void setMinTextSize(int minTextSize) {
this.minTextSize = minTextS
public float getMaxTextSize() {
return maxTextS
public void setMaxTextSize(int minTextSize) {
this.maxTextSize = minTextS
//Attributes
private Paint testP
private float minTextS
private float maxTextS}
找了一个代码,需要监听textview。
class LineTextWatcher implements TextWatcher {static final String TAG = "IpBike";TextView mTV;Paint mPpublic LineTextWatcher(TextView 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)
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)
// 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);
Log.v(TAG, "afterTextChanged Child not textView");
Log.v(TAG, "afterTextChanged parent not LinearLayout");
改变文字的大小
Spannable WordtoSpan = new SpannableString("大字小字");
WordtoSpan.setSpan(new AbsoluteSizeSpan(20), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
WordtoSpan.setSpan(new AbsoluteSizeSpan(14), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
remoteViews.setCharSequence(R.id.text11, "setText", WordtoSpan);
ComponentName com = new ComponentName("com.jftt.widget", "com.jftt.widget.MyWidgetProvider");
appWidgetManager.updateAppWidget(com, remoteViews);
来自http://txlong-onz.iteye.com/blog/1142781
获取屏幕的宽高,根据屏幕的宽高做一个算法计算字体大小不知是否可以实现你要的效果,方法是
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
System.out
.println("屏幕分辨率为:" + dm.widthPixels + " * " + dm.heightPixels);
这个问题看来只能用代码自己控制,计算字符串在给定字体下的显示宽度,进而找到最合适的字体大小。如果是用通常的TrueType字体,因为每个字符的显示宽度都是不同的,所以即便是相同长度的字符串的显示宽度也是不同的,因此必须根据每个字符串进行计算,可以使用字符的平均宽度进行预估,然后用两分法进行逼近,这个方法比较浪费计算资源。因此建议你可以使用字符显示宽度固定的字体,这样计算起来就非常容易了。这样的字体不多,我使用过,但是具体字体名字忘记了,使用这样的字体的显示效果也是不错的。
不是您所需,查看更多相关问题与答案
德问是一个专业的编程问答社区,请
后再提交答案
关注该问题的人
共被浏览 (26362) 次

我要回帖

更多关于 input text 文字大小 的文章

 

随机推荐