1、建立bean
public class UserBean {
private String mFirstName;
private String mLastName; public UserBean(String firstName, String lastName) {
this. mFirstName = firstName;
this. mLastName = lastName;
} public String getFirstName() {
return mFirstName;
} public String getLastName() {
return mLastName;
}
}
2、 建立model(处理业务逻辑,这里指数据读写),先写接口,后写实现
public interface IUserModel {
void setID(int id); void setFirstName(String firstName); void setLastName(String lastName); int getID(); UserBean load(int id);// 通过id读取user信息,返回一个UserBean
}
具体的实现可以自定义
3、建立view(更新ui中的view状态),这里列出需要操作当前view的方法,也是接口
public interface IUserView {
int getID(); String getFristName(); String getLastName(); void setFirstName(String firstName); void setLastName(String lastName);
}
4、建立presenter(主导器,通过iView和iModel接口操作model和view),activity可以把所有逻辑给presenter处理,这样java逻辑就从手机的activity中分离出来。
public class UserPresenter {
private IUserView mUserView;
private IUserModel mUserModel; public UserPresenter(IUserView view) {
mUserView = view;
mUserModel = new UserModel();
} public void saveUser( int id, String firstName, String lastName) {
mUserModel.setID(id);
mUserModel.setFirstName(firstName);
mUserModel.setLastName(lastName);
} public void loadUser( int id) {
UserBean user = mUserModel.load(id);
mUserView.setFirstName(user.getFirstName()); // 通过调用IUserView的方法来更新显示
mUserView.setLastName(user.getLastName());
}
}
5、activity中实现iview接口,在其中操作view,实例化一个presenter变量。
public class MainActivity extends Activity implements OnClickListener,IUserView { UserPresenter presenter;
EditText id,first,last;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout. activity_main); findViewById(R.id. save).setOnClickListener( this);
findViewById(R.id. load).setOnClickListener( this);
id = (EditText) findViewById(R.id. id);
first = (EditText) findViewById(R.id. first);
last = (EditText) findViewById(R.id. last); presenter = new UserPresenter( this);
} @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id. save:
presenter.saveUser(getID(), getFristName(), getLastName());
break;
case R.id. load:
presenter.loadUser(getID());
break;
default:
break;
}
} @Override
public int getID() {
return new Integer( id.getText().toString());
} @Override
public String getFristName() {
return first.getText().toString();
} @Override
public String getLastName() {
return last.getText().toString();
} @Override
public void setFirstName(String firstName) {
first.setText(firstName);
} @Override
public void setLastName(String lastName) {
last.setText(lastName);
} }
所谓的mvp,即是(model-处理业务逻辑(主要是数据读写,或者与后台通信(其实也是读写数据)),view-处理ui控件,presenter-主导器,操作model和view)