簡體   English   中英

在圖層演示者MVP上使用資源“ R.String”中的字符串

[英]Using Strings from resource “R.String” on layer presenter MVP

在MVP模式上,我具有動態值%的字符串

例:

<string name="hello">%s hello</string>

並且我需要在文本視圖中將此文本設置為“我的名字”,我將如何執行此引用而不直接在演示者層上使用R.String。

public void onItemClicked(String name) {
        if (mainView != null) {
             //HOW use R.string.hello from Strings  here? [presenter layer]
            mainView.showMessage(String.format("%s hello", name));
        }
    }

在MVP模式上,我無法在presenter層中引用任何Android類,我在此類中沒有任何上下文,但是我需要使用R.string.hello,因為翻譯,我如何才能用這種方式破壞了該MVP模式

快速解答:您不

您可以對代碼進行結構化,因此您的視圖方法為:

@Override
public void showMessage(String name){

    if (mTextView != null){
        mTextView.setText(String.format(getString(R.string.hello), name));
    }
}

然后,您的演示者代碼為:

public void onItemClicked(String name) {
    if (mainView != null) {
        mainView.showMessage(name);
    }
}

MVP是關於干凈的可測試代碼的,在這種情況下,您要在演示者中進行的所有測試就是演示者將正確的名稱傳遞給視圖。 您無需測試String.format()或從資源中獲取字符串(其他開發人員已經做到了這一點,即Android開發人員)。 我建議也許更深入地了解MVP為何會使您的項目受益

getString()有一個重載版本,它使用varargs進行格式化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM