Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android RoboGuice 使用指南(18):Inject Resources 注入資源

編輯:Android 開發教學

RoboGuice 對存取 res 目錄下的各類資源——drawable、array、string 等——也提供了注入支援。透過 @InjectResource,可以相当方便地把所需資源直接送進變數。

改造範例

本例修改 ApiDemos 中的 Content → Resources → Resources,改用 Inject Resource 的方式來存取資源。

public class InjectResourceDemo extends RoboActivity {

    @InjectView(R.id.styled_text) TextView styled_text;
    @InjectView(R.id.plain_text)  TextView plain_text;
    @InjectView(R.id.res1)        TextView res1;

    @Inject Resources res;
    @InjectResource(R.string.styled_text) String str;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.injectresource);

        // 用 res 取得字串資源
        CharSequence cs = res.getText(R.string.styled_text);

        // 注意這裡用的是 CharSequence 而非 String,
        // 這樣才不會失去樣式資訊
        styled_text.setText(cs);

        // 同一份資源,但轉成 String,
        // 這會導致樣式資訊遺失
        plain_text.setText(str);

        res1.setText(cs);
    }
}

CharSequence 與 String 的關鍵差別

這個範例最值得學的不是 @InjectResource,而是它刻意示範了 CharSequence 與 String 的差異。

Android 的字串資源檔支援 HTML 風格標記,例如 <b>、<i>、<font>。當你用 getText() 讀取時,回傳的是 CharSequence,樣式資訊完整保留,畫面上的文字該粗就粗、該斜就斜。

但一旦轉成 String,樣式就被抹平了——所有文字都變成同一種樣式。

這解釋了為什麼範例要準備 styled_text 與 plain_text 兩個 TextView 做對照:同樣的資源,用不同型別接收,呈現結果完全不同。

而 @InjectResource(R.string.styled_text) String str 這行,因為宣告型別是 String,框架會自動幫你完成轉換,也就順帶把樣式丟掉了。

實務建議

規則很簡單:只要資源檔裡可能有標記,就用 CharSequence 接收。用 getText() 而非 getString(),並把變數型別宣告為 CharSequence 或 Spanned。

另一個容易忽略的點是 @Inject Resources res 這行——它把 Resources 物件本身也注入了進來。這在需要動態決定資源 ID 的場景下很有用,例如依條件從陣列資源中挑字串,或格式化帶參數的 plurals。

本例子下載:https://www.imobilebbs.com/download/android/roboguice/InjectResourceDemo.zip

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved