Android---String资源文件中通过String.format()(动态改变)字符串资源的显示内容
例如:小明来自烟台年龄18岁性别男。其中,“小明”、“烟台”、“18”、“男”,均为可变的,就可以通过String.format()设置。
代码:
string.xml%1$s:来自%2$s,年龄%3$d,性别%4$s.
MainActivity.javaTextView tx = (TextView)findViewById(R.id.tx);
String userName = "小明";
String userArea = "烟台";
int age = 18;
String userSex = "男";
String Str = getResources( ).getString( R.string.formatStr);
String ss = String.format( Str,userName, userArea, age, userSex );
tx.setText( ss );
结果:
image.png
String.format()字符串常规类型格式化的两种重载方式format(String format, Object… args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字符串。
format(Locale locale, String format, Object… args) 使用指定的语言环境,制定字符串格式和参数生成格式化的字符串。
上例包括字符类型和整数类型的格式化,下表为常用的类型例举转换符详细说明示例%s字符串类型"简书"
%c字符类型'm'
%b布尔类型true
%d整数类型(十进制)88
%x整数类型(十六进制)FF
%o整数类型(八进制)77
%f浮点类型8.888
%a十六进制浮点类型FF.35AE
%e指数类型9.38e + 5
%g通用浮点类型(f和e类型中较短的)不举例(基本用不到)
%h散列码不举例(基本用不到)
%%百分比类型%(%特殊字符%%才能显示%)
%n换行符不举例(基本用不到)
%tx日期与时间类型(x代表不同的日期与时间转换符)不举例(基本用不到)
代码示例//例子
String str=null;
str=String.format("Hi,%s", "小明");
System.out.println(str);
str=String.format("Hi,%s %s %s", "小明","是个","学生");
System.out.println(str);
System.out.printf("字母c的大写是:%c %n", 'C');
System.out.printf("布尔结果是:%b %n", "小明".equals("学生"));
System.out.printf("100的一半是:%d %n", 100/2);
System.out.printf("100的16进制数是:%x %n", 100);
System.out.printf("100的8进制数是:%o %n", 100);
System.out.printf("50元的书打8.5折扣是:%f 元%n", 50*0.85);
System.out.printf("上面价格的16进制数是:%a %n", 50*0.85);
System.out.printf("上面价格的指数表示:%e %n", 50*0.85);
System.out.printf("上面价格的指数和浮点数结果的长度较短的是:%g %n", 50*0.85);
System.out.printf("上面的折扣是%d%% %n", 85);
System.out.printf("字母A的散列码是:%h %n", 'A');
运行结果
搭配转换符可实现高级功能 第一个例子中有用到 $转换符详细说明示例结果+为正数或者负数添加符号(“%+d”,15)+15
0数字前面补0(加密常用)(“%04d”, 99)0099
空格在整数之前添加指定数量的空格(“% 4d”, 99)99
,以“,”对数字分组(常用显示金额)(“%,f”, 9999.99)9,999.990000
(使用括号包含负数(“%(f”, -99.99)(99.990000)
#如果是浮点数则包含小数点,如果是16进制或8进制则添加0x或0(“%#x”, 99) (“%#o”, 99)0x63 0143
|被格式化的参数索引| ("d,%2$s”, 99,”abc”)99,abc
日期转换符转换符详细说明示例c包括全部日期和时间信息星期四 三月 1 14:21:20 CST 2007
F“年-月-日”格式2018-03-01
D“月/日/年”格式03/01/18
r“HH:MM:SS PM”格式(12时制)02:25:51 下午
T“HH:MM:SS”格式(24时制)14:28:16
R“HH:MM”格式(24时制)14:28
代码示例://例子
Date date=new Date(); //c的使用
System.out.printf("全部日期和时间信息:%tc%n",date); //f的使用
System.out.printf("年-月-日格式:%tF%n",date); //d的使用
System.out.printf("月/日/年格式:%tD%n",date); //r的使用
System.out.printf("HH:MM:SS PM格式(12时制):%tr%n",date); //t的使用
System.out.printf("HH:MM:SS格式(24时制):%tT%n",date); //R的使用
System.out.printf("HH:MM格式(24时制):%tR",date);
运行结果: