0

我是 Android 新手,正在尝试学习 MVP 模式。我写了下面的示例教程,它从 EditText 获取用户名和密码,看看它是否匹配“Don”和“Bradman”。如果是,它将相应地显示 Toast 消息。我的问题是

“可以从 Activity 中的 Edit Text 获取值并在那里进行比较吗?我不这么认为,因为业务逻辑进入 Activity,这不是正确的做法。如果是,那么我怎样才能获得这些编辑文本值Presenter 类并在那里匹配并向 Activity 发送消息以显示 Toast。下面是我的代码,如果有人可以帮助“:

主界面.java

public interface MainInterface {

    //Declare all Activity related methods here
    interface View{
        void checkLoginSuccessful();
    }

    //Declare all Model related methods here
    interface Model{
        String getUsername();
        String setUsername(String username);
        String getPassword();
        String setPassword(String password);
    }

    //Declare all Presenter related methods here -- All Business Logic comes here
    interface Presenter {
        void onClickLogin();
    }
}

PresenterClass.java

public class PresenterClass implements MainInterface.Presenter{

    //Now since presenter is going to interact with both classes Model and View so let's invoke both "DataModel" class and "MainActivity" class
    private MainInterface.View mview;


    public PresenterClass(MainInterface.View view) {
        this.mview = view;
    }


    @Override
    public void onClickLogin() {
        mview.checkLoginSuccessful();
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements MainInterface.View {

    private EditText username;
    private EditText password;
    private Button loginbutton;

    PresenterClass presenter;

    //DataModel data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        presenter = new PresenterClass(this);

        username = (EditText) findViewById(R.id.editusername);
        password = (EditText) findViewById(R.id.editpassword);
        loginbutton = (Button) findViewById(R.id.loginbutton);
        loginbutton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                presenter.onClickLogin();
            }
        });
    }

    @Override
    public void checkLoginSuccessful() {
        if (username.getText().toString().equals("Don") && password.getText().toString().equals("Bradman")){
            Toast.makeText(MainActivity.this, "You have successfully logged in", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(MainActivity.this, "Wrong Username or Password", Toast.LENGTH_SHORT).show();
        }
    }
}
4

1 回答 1

0

您需要在演示者调用的视图中添加两个方法来获取用户名和密码,一旦获得,您就可以进行所需的操作并调用该方法来显示 toast。

与模型有接口是没有意义的,模型是您域的对象,例如用户,并且用户具有用户名和密码字段,然后您将查看用户的数据并将其设置在对象,例如,将其保存在数据库中。

我希望它对你有所帮助。

于 2017-11-03T22:48:55.707 回答