效果图:
一个字符串中某些字符改变颜色或者字体大小的需求,之前一直使用Spannable处理,碰到这个发现如果使用Spannable就有点不方便了;这里使用了String.format来动态格式化String资源,使用CDATA来控制特定位置的样式;具体代码如下:
String.xml:
<resources>
<string name="app_name">Test</string>
<string name="content">本月应发工资:<![CDATA[<font color="#ff0000">%1$d</font>]]> 实发工资:<![CDATA[<font color="#ff0000">%2$d</font>]]>元(包含奖金<![CDATA[<font color="#ff0000">%3$d</font>]]>元)</string>
</resources>
MainActivity:
package com.example.administrator.test;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);
tv.setText(Html.fromHtml(String.format(getResources().getString(R.string.content),10,20,10)));
}
}
- String.format 格式化对应的转换符如下表
转换符 | 说明 |
---|---|
%s | 字符串类型 |
%c | 字符类型 |
%b | 布尔类型 |
%d | 整数类型(十进制) |
%x | 整数类型(十六进制) |
%o | 整数类型(八进制) |
%f | 浮点类型 |
%a | 十六进制浮点类型 |
%e | 指数类型 |
%g | 通用浮点类型(f和e类型中较短的) |
%h | 散列码 |
%% | 百分比类型 |
%n | 换行符 |
%tx | 日期与时间类型(x代表不同的日期与时间转换符 |