繁体   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