这里提供一个小小的例子。
layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="50dp" />
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="50dp"
android:inputType="numberPassword" />
<Button
android:id="@+id/login"
android:layout_width="match_parent"
android:layout_height="50dp" />
<TextView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="50dp" />
</LinearLayout>
要做的事情就是用户输入username和password,点击login按钮后,在show控件中显示登录失败或登陆成功。
model层接口:
public interface IMainModel {
boolean login(String username, String password);
}
model层实现:
public class MainModel implements IMainModel {
@Override
public boolean login(String username, String password) {
// 模拟网络,进行耗时操作
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(username.equals(password))
return true;
return false;
}
}
这里用户名和密码相同即为登陆成功,否则登陆失败。
view层接口:
public interface IMainView {
void show(String s);
}
Presenter层实现:
import android.os.Handler;
public class MainPresenter {
private IMainModel model;
private IMainView view;
private Handler handler = new Handler();
public MainPresenter() {
model = new MainModel();
}
public void setView(IMainView iUserView) {
this.view = iUserView;
}
// 使用handler开启子线程
public void login(final String username, final String password) {
handler.post(new Runnable() {
@Override
public void run() {
if (model.login(username, password)) {
view.show("登陆成功");
} else {
view.show("登陆失败");
}
}
});
}
}
由于Activity充当view层,所以实现view层接口。并持有presenter对象。
MainActivity.java:
public class MainActivity extends Activity implements View.OnClickListener , IMainView {
private EditText username, password;
private Button button;
private TextView show;
private MainPresenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
presenter = new MainPresenter();
// 将view层传入
presenter.setView(this);
username = (EditText) this.findViewById(R.id.username);
password = (EditText) this.findViewById(R.id.password);
button = (Button) this.findViewById(R.id.login);
show = (TextView) this.findViewById(R.id.show);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
String userName = username.getText().toString();
String passWord = password.getText().toString();
presenter.login(userName, passWord);
break;
}
}
@Override
public void show(String s) {
show.setText(s);
}
}
如此实现能让Activity不再那么臃肿不堪。耦合低较低。有点类似与观察者模式。