Android的TextView使用

数字格式化

        // 实例化DecimalFormat类的对象,并指定格式
        DecimalFormat df1 = new DecimalFormat("0.0");
        DecimalFormat df2 = new DecimalFormat("#.#");
        DecimalFormat df3 = new DecimalFormat("000.000");
        DecimalFormat df4 = new DecimalFormat("###.###");
        Scanner scan = new Scanner(System.in);
        System.out.print("请输入一个float类型的数字:");
        float f = scan.nextFloat();
        // 对输入的数字应用格式,并输出结果
        System.out.println("0.0 格式:" + df1.format(f));
        System.out.println("#.# 格式:" + df2.format(f));
        System.out.println("000.000 格式:" + df3.format(f));
        System.out.println("###.### 格式:" + df4.format(f));

AutoCompleteTextView 自动填充控件的属性和使用方式

autotext =(AutoCompleteTextView) findViewById(R.id.autotext);
String [] arr={"aa","aab","aac"};
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,arr);
//自定义的Adapter 需要实现Filterable
autotext.setAdapter(arrayAdapter);
AutoCompleteTextView常用属性 
android:completionHint 设置出现在下拉菜单中的提示标题
android:completionThreshold 设置用户至少输入多少个字符才会显示提示
android:dropDownHorizontalOffset 下拉菜单于文本框之间的水平偏移。默认与文本框左对齐
android:dropDownHeight 下拉菜单的高度
android:dropDownWidth 下拉菜单的宽度
android:dropDownAnchor 设置下拉菜单的定位"锚点"组件,如果没有指定改属性, 将使用该TextView作为定位"锚点"组件
android:dropDownSelector 设置下拉菜单点击效果
android:singleLine 单行显示
android:dropDownVerticalOffset 垂直偏移量
android:completionHintView 定义提示视图中显示下拉菜单
android:popupBackground 设置下拉菜单的背景

高亮、大小、字体

在这里插入图片描述

设置自定义字体
Spannable spannable = new SpannableString(firstWord+lastWord);
spannable.setSpan( new CustomTypefaceSpan("SFUIText-Bold.otf",fontBold), 0, firstWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan( new CustomTypefaceSpan("SFUIText-Regular.otf",fontRegular), firstWord.length(), firstWord.length() + lastWord.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
text.setText( spannable );

SpannableString spannable = new SpannableString(str);
//设置删除线
spannable.setSpan(new StrikethroughSpan(), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置下划线
spannable.setSpan(new UnderlineSpan(), 0, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置文字前景色 文本高亮
spannable.setSpan(new ForegroundColorSpan(Color.RED), 0, 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置字体的大小
spannable.setSpan(new RelativeSizeSpan(0.8f), 0, 10, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置超链接
spannable.setSpan(new URLSpan("tel:123456"), 0, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置斜体
spannable.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 0, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置图片资源来替换文本
spannable.setSpan(new ImageSpan(context, 0), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//设置点击事件
spannable.setSpan(new ClickableSpan() {
    @Override
    public void onClick(@NonNull View widget) {

    }
}, 0, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
flags:取值有如下四个
Spannable. SPAN_INCLUSIVE_EXCLUSIVE:前面包括,后面不包括,即在文本前插入新的文本会应用该样式,而在文本后插入新文本不会应用该样式
Spannable. SPAN_INCLUSIVE_INCLUSIVE:前面包括,后面包括,即在文本前插入新的文本会应用该样式,而在文本后插入新文本也会应用该样式
Spannable. SPAN_EXCLUSIVE_EXCLUSIVE:前面不包括,后面不包括
Spannable. SPAN_EXCLUSIVE_INCLUSIVE:前面不包括,后面包括

自定义字体

public class CustomTypefaceSpan extends TypefaceSpan { private final Typeface newType;
public CustomTypefaceSpan(String family, Typeface type) { super(family);
        newType = type;
    }
@Override
public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }
@Override
public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }
private static void applyCustomTypeFace(Paint paint, Typeface tf) { int oldStyle;
Typeface old = paint.getTypeface(); if (old == null) {
oldStyle = 0; } else {
            oldStyle = old.getStyle();
        }
int fake = oldStyle & ~tf.getStyle(); if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true); }
if ((fake & Typeface.ITALIC) != 0) { paint.setTextSkewX(-0.25f);
}
        paint.setTypeface(tf);
    }
}

加删除线

全部加删除线
String sampleText = "This is a test strike";
textView.setPaintFlags(tv.getPaintFlags()| Paint.STRIKE_THRU_TEXT_FLAG);
textView.setText(sampleText);

自定义文字位置

TextView txtView = (TextView) findViewById(R.id.txtView);
SpannableString spannableString = new SpannableString("RM123.456"); 
spannableString.setSpan( new TopAlignSuperscriptSpan( (float)0.35 ), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
txtView.setText(spannableString);

TopAlignSuperscriptSpan.java
private class TopAlignSuperscriptSpan extends SuperscriptSpan {
//divide superscript by this number
protected int fontScale = 2;
    //shift value, 0 to 1.0
protected float shiftPercentage = 0; //doesn't shift
    TopAlignSuperscriptSpan() {}
    //sets the shift percentage
TopAlignSuperscriptSpan( float shiftPercentage ) {
if( shiftPercentage > 0.0 && shiftPercentage < 1.0 )
this.shiftPercentage = shiftPercentage;
}
@Override
public void updateDrawState( TextPaint tp ) {
        //original ascent
float ascent = tp.ascent(); //scale down the font
tp.setTextSize( tp.getTextSize() / fontScale ); //get the new font ascent
float newAscent = tp.getFontMetrics().ascent;
//move baseline to top of old font, then move down size of new font //adjust for errors with shift percentage
tp.baselineShift += ( ascent - ascent * shiftPercentage )
                - (newAscent - newAscent * shiftPercentage );
}
@Override
public void updateMeasureState( TextPaint tp ) {
        updateDrawState( tp );
    }
}

文本设置图片

//方法一
Drawable drawable = tv.getResources().getDrawable(resId);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
tv.setCompoundDrawables(null, null, drawable, null);

//方法二
public static void setTvDrawable(TextView tv, String content, int resId, int type) {
    ImageSpan span = new ImageSpan(tv.getContext().getResources().getDrawable(resId));
	SpannableString spanStr = null;
	if (0 == type) {
          spanStr = new SpannableString(content);
	} else if (1 == type) {
          spanStr = new SpannableString("0" + content);
          spanStr.setSpan(span, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
	} else if (2 == type) {
		spanStr = new SpannableString(content + "0");
		spanStr.setSpan(span, spanStr.length() - 1, spanStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
	}
	tv.setText(spanStr);
}

选中下滑线

 /**
     * TextView选中下滑线
     */
    private void setTabSelected(TextView btnSelected) {
        Drawable selectedDrawable = ContextCompat.getDrawable(activity, R.drawable.shape_nav_indicator);
        int screenWidth = QMUIDisplayHelper.getRealScreenSize(activity)[0];
        int right = screenWidth / 2;
        selectedDrawable.setBounds(0, 0, right, QMUIDisplayHelper.dp2px(activity, 3));
        btnSelected.setCompoundDrawables(null, null, null, selectedDrawable);
        int size = ll_home.getChildCount();
        for (int i = 0; i < size; i++) {
            if (btnSelected.getId() != ll_home.getChildAt(i).getId()) {
                ll_home.getChildAt(i).setSelected(false);
                ((TextView) ll_home.getChildAt(i)).setCompoundDrawables(null, null, null, null);
            }
      }
}

利用HTML增加图片

 private fun changeHtml(content: kotlin.String): Spanned {
        return Html.fromHtml("<img src='123'/> $content", Html.ImageGetter {
            var drawable = mContext.resources.getDrawable(R.drawable.icon_call_black)
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight())
            drawable
        }, null)
    }

TextView的内容自增长

    public static void autoIncrement(final TextView target, final int start,
                                     final int end, long duration) {
        ValueAnimator animator = ValueAnimator.ofFloat(start, end);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            private FloatEvaluator evalutor = new FloatEvaluator();
            private DecimalFormat format = new DecimalFormat("####0.00");
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float fraction = animation.getAnimatedFraction();
                float currentValue = evalutor.evaluate(fraction, start, end);
                target.setText(format.format(currentValue));
            }
        });
        animator.setDuration(duration);
        animator.start();
    }

自定义相关内容

msp = new SpannableString("字体测试字体大小一半两倍前景色背景色正常粗体斜体粗斜体下划线删除线x1x2电话邮件网站短信彩信地图X轴综合");   
//设置字体(default,default-bold,monospace,serif,sans-serif) 
 msp.setSpan(new TypefaceSpan("monospace"), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
 msp.setSpan(new TypefaceSpan("serif"), 2, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

//设置字体大小(绝对值,单位:像素)   
msp.setSpan(new AbsoluteSizeSpan(20), 4, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
msp.setSpan(new AbsoluteSizeSpan(20,true), 6, 8, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //第二个参数boolean dip,如果为true,表示前面的字体大小单位为dip,否则为像素,同上。 

//设置字体大小(相对值,单位:像素) 参数表示为默认字体大小的多少倍 
 msp.setSpan(new RelativeSizeSpan(0.5f), 8, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //0.5f表示默认字体大小的一半 
msp.setSpan(new RelativeSizeSpan(2.0f), 10, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //2.0f表示默认字体大小的两倍 

//设置字体前景色 
msp.setSpan(new ForegroundColorSpan(Color.MAGENTA), 12, 15, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置前景色为洋红色 

//设置字体背景色 
msp.setSpan(new BackgroundColorSpan(Color.CYAN), 15, 18, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //设置背景色为青色 

//设置字体样式正常,粗体,斜体,粗斜体 
msp.setSpan(new StyleSpan(android.graphics.Typeface.NORMAL), 18, 20, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //正常 
msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 20, 22, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //粗体 
msp.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 22, 24, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //斜体 
msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 24, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //粗斜体 

//设置下划线 
msp.setSpan(new UnderlineSpan(), 27, 30, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

//设置删除线 
msp.setSpan(new StrikethroughSpan(), 30, 33, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 

//设置上下标 
msp.setSpan(new SubscriptSpan(), 34, 35, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);     //下标     
msp.setSpan(new SuperscriptSpan(), 36, 37, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);   //上标             

//超级链接(需要添加setMovementMethod方法附加响应) 
msp.setSpan(new URLSpan("tel:4155551212"), 37, 39, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);     //电话     
msp.setSpan(new URLSpan("mailto:webmaster@google.com"), 39, 41, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);     //邮件     
msp.setSpan(new URLSpan("http://www.baidu.com"), 41, 43, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);     //网络     
msp.setSpan(new URLSpan("sms:4155551212"), 43, 45, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);     //短信   使用sms:或者smsto: 
msp.setSpan(new URLSpan("mms:4155551212"), 45, 47, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);     //彩信   使用mms:或者mmsto: 
msp.setSpan(new URLSpan("geo:38.899533,-77.036476"), 47, 49, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);     //地图     

//设置字体大小(相对值,单位:像素) 参数表示为默认字体宽度的多少倍 
msp.setSpan(new ScaleXSpan(2.0f), 49, 51, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //2.0f表示默认字体宽度的两倍,即X轴方向放大为默认字体的两倍,而高度不变 
//SpannableString对象设置给TextView 
myTextView.setText(msp);   
//设置TextView可点击 
myTextView.setMovementMethod(LinkMovementMethod.getInstance());

Drawable drawable= getResources().getDrawable(R.drawable.drawable); 
/// 这一步必须要做,否则不会显示. 
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); 
方法一:myTextview.setCompoundDrawables(drawable,null,null,null); 
方法二: myTextview.setCompoundDrawablesWithIntrinsicBounds(drawable,null,null,null);

计算文本的宽和高

    // 测试字符串
    // 测试例子均用15sp的字体大小
    String text = "测试中文";
    TextView textView = (TextView) findViewById(R.id.test);
    textView.setText(text);
     //方法一 此方法获得是Int型
    int spec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
    textView.measure(spec, spec);
    // getMeasuredWidth 
    int measuredWidth = textView.getMeasuredWidth();
     
    //方法二  获得的宽度不准确 有英文的时候会测量不准确
    // new textpaint measureText
    TextPaint newPaint = new TextPaint();
    float textSize = getResources().getDisplayMetrics().scaledDensity * 15;
    newPaint.setTextSize(textSize);
    float newPaintWidth = newPaint.measureText(text);

     // 方法三 可以获得文本的Float型文本宽度
    // textView getPaint measureText
    TextPaint textPaint = textView.getPaint();
    float textPaintWidth = textPaint.measureText(text);

    Log.i(TAG, "测试字符串:" + text);
    Log.i(TAG, "getMeasuredWidth:" + measuredWidth);
    Log.i(TAG, "newPaint measureText:" + newPaintWidth);
    Log.i(TAG, "textView getPaint measureText:" + textPaintWidth);
    当测试字符串为: “测试中文”时,结果如下 :

   测试字符串:测试中文
  getMeasuredWidth:180
  measureText:180.0
  getPaint measureText:180.0
  当测试字符串为: “测试英文abcd”时,

  测试字符串:测试英文abcd
  getMeasuredWidth:279
  newPaint measureText:278.0
  getPaint measureText:279.0 
  当设置换行的时候 
  text.setText("测试\n中文");可以换行
  当是字符串的时候:String str = "测试\n中文";
  此时应该这么处理 str=str.replace("\\n","\n"); 
 注:
     android:ellipsize="none"
     android:maxLines="4"
     android:scrollHorizontally="false"

部分字体高亮

            String labelStr = "购物满"+fullNum+"件";
                int bstart=labelStr.indexOf(fullNum);
                int bend=bstart+fullNum.length();
                SpannableStringBuilder style=new SpannableStringBuilder(labelStr);
                style.setSpan(new ForegroundColorSpan(Color.parseColor("#FF4E00")),bstart,bend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                labelName.setText(style);
                SpannableStringBuilder builder = new SpannableStringBuilder(labelStr);
                ForegroundColorSpan juSpan = new ForegroundColorSpan(Color.parseColor("#FF4E00"));
                builder.setSpan(juSpan, 3, labelStr.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                labelName.setText(builder);

SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString()); 

//ForegroundColorSpan 为文字前景色,BackgroundColorSpan为文字背景色 
ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED); 
ForegroundColorSpan whiteSpan = new ForegroundColorSpan(Color.WHITE); 
ForegroundColorSpan blueSpan = new ForegroundColorSpan(Color.BLUE); 
ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.GREEN); 
ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.YELLOW); 



builder.setSpan(redSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
builder.setSpan(whiteSpan, 1, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 
builder.setSpan(blueSpan, 2, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
builder.setSpan(greenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
builder.setSpan(yellowSpan, 4,5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

textView.setText(builder);

tv = (TextView) this .findViewById(R.id. text_view );
中间加横线
tv.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
底部加横线:
tv .getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
TextVIew 的Html解析方法:
textView.setText(Html.fromHtml("<u>"+"字符串信息"+"</u>"));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值