我是 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();
}
}
}