写一个Activity父类:
public abstract class BaseActivity extends Activity {
//找到所有控件id
public abstract void initView();
//数据初始化
public abstract void initData();
//监听回调
public abstract void initListener();
}
展示功能的Activity:
public class MainActivity extends BaseActivity implements UserView, OnClickListener{
private TextView mTv;
private Button mBtn;
private ProgressDialog mProgressDialog;
private UserPresenter mUserPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
initListener();
}
@Override
public void initView() {
mTv = (TextView) findViewById(R.id.tv);
mBtn = (Button) findViewById(R.id.btn);
}
@Override
public void initData() {
mUserPresenter = new UserPresenter(this);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("提示");
mProgressDialog.setMessage("正在加载...");
mProgressDialog.setCanceledOnTouchOutside(false);
}
@Override
public void initListener() {
mBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
mUserPresenter.getUser();
break;
default:
break;
}
}
@Override
public void updateView(User user) {
mTv.setText(user.getUserName());
}
@Override
public void showProgressDialog() {
mProgressDialog.show();
}
@Override
public void hideProgressDialog() {
mProgressDialog.hide();
}
@Override
public void showError(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
写一个JavaBean:
public class User {
private String userName;
public User(String userName){
this.userName=userName;
}
public String getUserName(){
return userName;
}
}
MVP中的M(modle):
public class UserModle {
public Observable<User> getUser(){
return Observable.create(new OnSubscribe<User>() {
@Override
public void call(Subscriber<? super User> sub) {
SystemClock.sleep(1000);
User user=new User("阿毛是SB");
if(user==null){
sub.onError(new Exception("User=null"));
}else{
sub.onNext(user);
sub.onCompleted();
}
}
});
}
}
MVP中的V(view):
public interface UserView {
void updateView(User user);
void showProgressDialog();
void hideProgressDialog();
void showError(String msg);
}
MVP中的P(Presenter):
public class UserPresenter {
private UserView mUserView;
private UserModle mUserModle;
public UserPresenter(UserView userView){
mUserView=userView;
mUserModle=new UserModle();
}
public void getUser(){
mUserView.showProgressDialog();
mUserModle.getUser()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<User>() {
@Override
public void onCompleted() {
mUserView.hideProgressDialog();
}
@Override
public void onError(Throwable t) {
mUserView.showError(t.getMessage());
mUserView.hideProgressDialog();
}
@Override
public void onNext(User user) {
mUserView.updateView(user);
}
});
}
}
效果就不展示了,只是感觉RxJava很强大,大家也可以自行研究相互交流。