AndroidStudio筆記(7)字串格式
引言
本篇記錄一些其他的技巧:字串的格式化、佔位符的使用
字串格式化
我們先看看下面這個例子:
ofollow,noindex">你好,我的名字是aohanyao,今年26歲,我的郵箱是[email protected] ,以下是浮點數:1234.00
而我們的需求是名字、年齡和郵箱是需要動態替換的,大多數人實現的方式如下:
String mIntroduction="你好,我的名字是"+name+",今年"+age+"歲,我的郵箱是"+email
咋看上去好像沒什麼毛病,但實際上這並不是一個好的做法,這樣等同於把字串硬編碼到程式碼中了,可擴充套件性和維護性變得極差,而我們應該使用 string resource 來進行引用。
開始編碼
首先在string.xml中建立相應的字串資源如下:
<string name="introduction">你好,我的名字是%s,今年%d歲,我的郵箱是%s。</string>
- %d (表示整數)
- %s (表示字串)
- %f (表示浮點數)
在程式碼中進行引用:
TextView tv_introduction = findViewById(R.id.tv_introduction); tv_introduction.setText(getResources().getString(R.string.introduction, "aohanyao", 26, "[email protected]"));
看看效果:
最後
AndroidRoad/tree/master/StringFormart" target="_blank" rel="nofollow,noindex">原始碼