简介:


%n$ms$s代表输出的是字符串,%n代表是第几个参数,设置m的值可以在输出之前放置空格

%n$md$d代表输出的是整数,%n代表是第几个参数,设置m的值可以在输出之前放置空格

%n$mf$f代表输出的是浮点数,%n是第几个参数,m在浮点类型之前设置几个空格 , 设置m的值可以控制小数位数,如m=2.2时,输出格式为00.00

注:%数字表示替换字符串中要替换的位置,若一个字符串要替换两个int类型,在替换位置分别 写%1$d%2$d.

%s%d为缩写方式,只替换一个位置。

demo 一 :

strings.xml:

<string name="person">我叫%1$s,现在生活在%2$s</string>
<string name="count">我今天吃了%1$4d个苹果</string>
<string name="money">我今天花了%1$15.2f元</string>

布局:

<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@android:color/white"
    tools:text="@tools:sample/cities" />

<TextView
    android:id="@+id/tv2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@android:color/white"
    tools:text="@tools:sample/cities" />

<TextView
    android:id="@+id/tv3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@android:color/white"
    tools:text="@tools:sample/cities" />

代码:

TextView mTv1 = (TextView) findViewById(R.id.tv1);
mTv1.setText(String.format(getString(R.string.person), "周杰伦", "台湾省"));

TextView mTv2 = (TextView) findViewById(R.id.tv2);
mTv2.setText(String.format(getString(R.string.count), 3));

TextView mTv3 = (TextView) findViewById(R.id.tv3);
mTv3.setText(String.format(getString(R.string.money), 195.1255));

demo 二 :

1.在strings.xml中定义

我叫%1$s,我%2$s贼溜,我段位王者%3$d,不信可以%4$s一起玩!

2.在类中调用

String.format(mActivity.getResources().getString(R.string.tips),"张三“,”吃鸡“,1,”晚上“))

输出结果就会拼接上。

输出结果:

我叫张三,我吃鸡贼溜,我段位王者1,不信可以晚上一起玩!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐