![](http://hi.csdn.net/attachment/201108/2/0_13122699946ZR0.gif)
![](http://hi.csdn.net/attachment/201108/2/0_1312270017x033.gif)
如何android字符中动态的显示数字呢?
答案应该有多种,但是在Android建议这么做:
首先定义字符串资源文件:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="app_name">TestDinamicNum</string>
<string name="unread_notification">有(<xliff:g id="number">%1$d</xliff:g>)条未读信息</string>
</resources>
然后在编写源代码文件:
private static int num = 1;
private TextView test = null;
private TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
myHandler.sendMessage(message);
}
};
private Handler myHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch(msg.what) {
case 1:
updateNum();
break;
}
};
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
test = (TextView) findViewById(R.id.tv);
new Timer().schedule(timerTask, new Date(), 5000);
}
private void updateNum() {
num++;
test.setText(getString(R.string.unread_notification, num));
}
最后运行,显示如上图的结果。
这里有两点容易出问题的
1.在第一行中容易出现空格,程序会报错
2.在resources中未声明。