有一段时间没有更新博客了,感觉有些懒惰了,懒惰是一个非常不好的习惯,必须要想法子戒掉,不能上瘾。
假如我们现在有一个UI效果图,上面有一行文字有比如 50%的字样。很明显后面的%字体大小和颜色都和前面的 50 不一样。按照常规思路很简单,实现起来就是使用两个textview,分别设置不同的字体大小和颜色就行了。
这是常规方法,如果我们不想使用两个textview来做,能不能使用一个textview来实现呢,当然是可以的,自定义一个就行了。
实现思路:
- 确定需要自定义的属性
因为需要使用自定义控件,所以就需要根据最终效果确定需要自定义的属性,在本例中50 和 % 明显的字体大小和颜色不一样,所以本例中主要有三个自定义属性:要缩小或者放大部分的文本内容、字体大小、字体颜色
private int small_text_color;
private int small_text_size;
private String small_text;
- 定义属性文件
自定义属性文件的过程就不做过多说明了,这里给出本例中的属性文件内容:
<resources>
<declare-styleable name="Custom_AutoSize_TextView">
<attr name="small_text_color" format="color"/>
<attr name="small_text" format="string"/>
<attr name="small_text_size" format="dimension"/>
</declare-styleable>
</resources>
由于字体大小dp作为单位,所以这里的格式使用的是dimension
3. 自定义textview
这里给出核心部分
public void getAttrs(Context context,AttributeSet attrs){
TypedArray array = context.obtainStyledAttributes(attrs,R.styleable.Custom_AutoSize_TextView);
small_text = array.getString(R.styleable.Custom_AutoSize_TextView_small_text);
small_text_color = array.getColor(R.styleable.Custom_AutoSize_TextView_small_text_color, Color.BLACK);
small_text_size = array.getDimensionPixelSize(R.styleable.Custom_AutoSize_TextView_small_text_size,12);
array.recycle();
initView();
}
public void initView(){
text = getText().toString();
if(!text.contains(small_text)){
return;
}
// 这里的逻辑是这样的,由于我们要实现的是同一个textview不同字体大小和颜色的效果,所以需要明确哪一部分的文字要变小放大或者更改颜色
// 而所有的操作都是基于原始内容之上进行的,所以需要确定需要修改的那一部分文字在原字符串中的起始位置
// 同时也需要根据起始位置和small——text的长度确定结束位置
int start=text.indexOf(small_text);
int end=text.indexOf(small_text)+small_text.length();
//设置颜色
SpannableString spannableString = new SpannableString(text);
spannableString.setSpan(new ForegroundColorSpan(small_text_color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
// text.replace(small_text,spannableString);
// 设置大小
spannableString.setSpan(new AbsoluteSizeSpan(small_text_size),start,end,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
setText(spannableString);
}
- 具体使用
在布局文件中引入该自定义view:
<com.henkun.customautosizetextview.Custom_AutoSize_TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4.30%"
app:small_text="%"
android:textSize="25dp"
app:small_text_size="20dp"
app:small_text_color="#00ffff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
- 说明 上面的过程只能实现在布局文件中修改字体的大小和颜色,如果要想在代码中实现本文开始的效果,还需要稍作修改,下次介绍一下如何修改。