androidmvppresenter

Using Strings from resource "R.String" on layer presenter MVP


On MVP pattern, i have string with dynamic value %

Example:

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

and i need set this text with "my name" on my textview, how i will do this witout reference direct a R.String on my presenter layer.

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));
        }
    }

On MVP pattern i cant have any reference an Android class in presenter layer, i dont have any context in this class, but i need use R.string.hello, because translate, how i can take this witouth ruins this MVP pattern


Solution

  • Quick answer: you don't

    You structure your code so your view method is:

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

    Then your presenter code is:

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

    MVP is all about clean testable code, in this case all you want to be testing within your presenter is that the presenter passes the correct name to the view. You don't need to be testing String.format() or getting strings from resources (other developers have already done this, ie. the Android devs). I suggest maybe reading a bit deeper into why MVP will benefit your project