android string.xml文件中的整型和string型代替
16lz
2021-01-26
在android的开发中,经常会遇见一句话,比如“我今年23岁了”;这个23需要在程序中生成,但是遇到一个问题,这完整的一句话是一个TextView中的,而不是三个textView拼接成的,而且是引用的string.xml文件中写好的;使用字符串拼接也可以实现,但是特别麻烦; 今天遇到一个好方法,在string.xml中,不仅可以设置文字的格式换行等,还可以设置类似于变量的文本格式; 1、整型,比如“我今年23岁了”,这个23是整型的。在string.xml中可以这样写,<string name="old">我今年%1$d岁了</string> 在程序中,使用 String sAgeFormat = getResources().getString(R.string.old); String sFinalAge = String.format(sAgeFormat, 23); 将%1$d替换为23; %1$d表达的意思是整个name=”old”中,第一个整型的替代。如果一个name中有两个需要替换的整型内容,则第二个写为:%2$d,以此类推;具体程序中替换见下面的string型; 2、string型,比如“我的名字叫李四,我来自首都北京”;这里的“李四”和“首都北京”都需要替换。 在string.xml中可以这样写,<string name="alert">我的名字叫%1$s,我来自%2$s</string> 在程序中: String sAgeFormat1 = getResources().getString(R.string.alert);
String sFinal1 = String.format(sAgeFormat1, "李四","首都北京"); 这里两个string需要替换的,按照上面程序的顺序依次对应。 package com.henzil.string; import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView; public class TihuanDemoActivity extends Activity {
/** Called when the activity is first created. */
private TextView oo,alert;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
oo = (TextView)findViewById(R.id.oo);
alert = (TextView)findViewById(R.id.alert);
String sAgeFormat = getResources().getString(R.string.oo); String sFinalAge = String.format(sAgeFormat, 1);
oo.setText(sFinalAge);
String sAgeFormat1 = getResources().getString(R.string.alert);
String sFinal1 = String.format(sAgeFormat1, "����","23");
alert.setText(sFinal1);
}
}
String sFinal1 = String.format(sAgeFormat1, "李四","首都北京"); 这里两个string需要替换的,按照上面程序的顺序依次对应。 package com.henzil.string; import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView; public class TihuanDemoActivity extends Activity {
/** Called when the activity is first created. */
private TextView oo,alert;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
oo = (TextView)findViewById(R.id.oo);
alert = (TextView)findViewById(R.id.alert);
String sAgeFormat = getResources().getString(R.string.oo); String sFinalAge = String.format(sAgeFormat, 1);
oo.setText(sFinalAge);
String sAgeFormat1 = getResources().getString(R.string.alert);
String sFinal1 = String.format(sAgeFormat1, "����","23");
alert.setText(sFinal1);
}
}
更多相关文章
- java后台程序员转android 《三》之 集成腾讯云 云直播 直播推流
- ContentResolver
- Android开发环境搭建:SDK在线离线安装+在Eclipse中配置ADT+第一个
- 你真的了解Instant Run吗?
- Android亮屏和熄屏控制实例详解
- Android(安卓)API Guides---Host-based Card Emulation
- 为Android应用程序读取/dev下设备而提权(一)
- APKBUS携手程序员们庆端午
- ”Android(安卓)Application Framework FAQ“关于Android框架的