MVP use and Activity encapsulation, mvpactivity Encapsulation
MVP use and Activity encapsulation.
MVP1. what is MVP
MVP is Model-View-Presenter, M: business logic and entity Model V: corresponds to Activity, is responsible for drawing view and user interaction P: Is responsible for connecting V and M
2. Benefits of MVP in Android
Mvp is a design pattern, which has different encapsulation forms based on different business scenarios.
Apply to Android:
?? 1. It reduces the Activity's responsibilities and simplifies the Activity code.
?? 2. Let the Activity focus on view processing and user interaction. The specific logic and data processing are handed over to the Presenter for processing.
?? 3. Lower code coupling and clearly differentiate module responsibilities.
?? 4. More flexible and robust code.
3. Use MVP in my project.
V's top-level interface View. The user connects Activity and Presenter.
public interface View {}
IPresenter, recording the Presenter Lifecycle
public interface IPresenter { void onCreate(); void onStart(); void onPause(); void onStop(); void onDestroy();}
Presenter, which uses generics to create a relationship with the View.
Public class Presenter
Implements IPresenter {private V view;/*** bind presenter and view ** @ param view */public void attachView (V view) {this. view = view;}/*** get current interface */protected V getView () {return view;} @ Override public void onCreate () {if (useEventBus ()&&! EventBus. getDefault (). isRegistered (this) EventBus. getDefault (). register (this) ;}@ Override public void onStart () {// Unused} @ Override public void onPause () {// Unused} @ Override public void onStop () {// Unused}/*** unbind interface and presenter */@ Override public void onDestroy () {if (useEventBus ()) // if you want to use eventbus, return true EventBus. getDefault (). unregister (this); if (view! = Null) {view = null ;}/ *** whether to use eventBus. Default Value: false, */protected boolean useEventBus () {return false ;}}
Extract common BaseActivity
1. Extract ideas
Just like the Prestener defined above, because the P layer is mainly used to process business logic, for example, it may receive some EventBus events, so a method is defined in the Prestener
/*** Whether to use eventBus. The default value is false. */protected boolean useEventBus () {return false ;}
When P is in onCreate (), we register:
if (useEventBus() && !EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this);
Similarly, cancel registration when P is destroyed:
if (useEventBus()) EventBus.getDefault().unregister(this);
In this way, when we need to use EventBus, we only need to re-write useEventBus () in P.
For Activity, we can also perform similar processing.
1. In-play animation of Activity
/*** Enumeration classes for page switching animation */public enum TransitionMode {FADE, LEFT2RIGHT}
Execute the logic of switching the animation when the Activity is started and destroyed.
// Start the Custom Import and Export animation if (isCustomPendingTransition () {switch (getCustomPendingTransitionType () {case FADE: overridePendingTransition (R. anim. fade_in, R. anim. fade_out); break; case LEFT2RIGHT: overridePendingTransition (R. anim. left_in, R. anim. rig); break ;}}
2. Activity jump Encapsulation
Activity performs jump extraction to Base class
/*************************************** *********************************** * ***** // *** Jump to another activity ** @ param clazz */protected void go (Class
Clazz) {Intent intent = new Intent (this, clazz); startActivity (intent );} /*** jump to another activity and pass the parameter ** @ param clazz * @ param bundle */protected void go (Class
Clazz, Bundle bundle) {Intent intent = new Intent (this, clazz); if (null! = Bundle) {intent. putExtras (bundle);} startActivity (intent);}/*** jump to another activity and end the current ** @ param clazz */protected void goThenKill (Class
Clazz) {Intent intent = new Intent (this, clazz); startActivity (intent); finish () ;}/ *** jump to another activity and end, and pass the parameter ** @ param clazz * @ param bundle */protected void goThenKill (Class
Clazz, Bundle bundle) {Intent intent = new Intent (this, clazz); if (null! = Bundle) {intent. putExtras (bundle);} startActivity (intent); finish ();}/*** starts an activity, and wait for the returned result ** @ param clazz * @ param requestCode */protected void goForResult (Class
Clazz, int requestCode) {Intent intent = new Intent (this, clazz); startActivityForResult (intent, requestCode);}/*** starts an activity and waits for the returned result, and pass the parameter ** @ param clazz * @ param requestCode * @ param bundle */protected void goForResult (Class
Clazz, int requestCode, Bundle bundle) {Intent intent = new Intent (this, clazz); if (null! = Bundle) {intent. putExtras (bundle);} startActivityForResult (intent, requestCode );} /*************************************** *********************************** ******/
3. Manage the keyboard contraction
@Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { android.view.View v = getCurrentFocus(); if (isShouldHideInput(v, ev)) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } return super.dispatchTouchEvent(ev); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); } private boolean isShouldHideInput(android.view.View v, MotionEvent event) { if (v != null && (v instanceof EditText)) { int[] location = {0, 0}; v.getLocationOnScreen(location); int left = location[0]; int top = location[1]; if (event.getX() < left || (event.getX() > left + v.getWidth()) || event.getY() < top || (event.getY() > top + v.getHeight())) { return true; } else { return false; } } return false; }
4. Define an abstract Method for The subclass to be rewritten.
In the onCreate method of BaseActivity
setContentView(setLayoutId()); initView(); initEvents();
Define the following abstract method in the class to rewrite the subclass.
/*** Set layout id */protected abstract int setLayoutId ();/*** Initialize all la S */protected abstract void initView (); /*** Initialize all event Events */protected abstract void initEvents ();
This basically all Activity is extracted. In the future, you can enrich it based on specific business scenarios.
The complete BaseActivity is as follows:
public abstract class BaseActivity
Extends FragmentActivity implements View {protected P mPresenter; @ Override public void onCreate (Bundle savedInstanceState) {// MyApplication. getInstance (). addActivity (this); // start custom in and out animation if (isCustomPendingTransition () {switch (getCustomPendingTransitionType () {case FADE: // overridePendingTransition (R. anim. fade_in, R. anim. fade_out); break; case LEFT2RIGHT: // overridePendingTransition (R. anim. left_in, R. anim. rig); break;} super. onCreate (savedInstanceState); mPresenter = createPresenter (); mPresenter. onCreate (); mPresenter. attachView (this); setContentView (setLayoutId (); initView (); initEvents () ;}@ Override public void finish () {super. finish (); if (isCustomPendingTransition () {switch (getCustomPendingTransitionType () {case FADE: // overridePendingTransition (R. anim. fade_in, R. anim. fade_out); break ;}}@ Override protected void onDestroy () {super. onDestroy (); // MyApplication. getInstance (). removeActivity (this); // unbind presenter mPresenter. onDestroy (); mPresenter = null;} protected abstract P createPresenter (); /*************************************** ********************************** * ****** // Several page switching animation enumeration Classes */public enum TransitionMode {FADE, LEFT2RIGHT}/*** @ return true -- custom page switching animation false -- not custom */protected boolean isCustomPendingTransition () {return false ;} /*** @ return the Custom Animation switching mode */protected TransitionMode getCustomPendingTransitionType () {return TransitionMode. FADE ;} /*************************************** ********************************** *******//******************************* *************************** * ************ // *** jump to another activity ** @ param clazz */protected void go (Class Clazz) {Intent intent = new Intent (this, clazz); startActivity (intent );} /*** jump to another activity and pass the parameter ** @ param clazz * @ param bundle */protected void go (Class Clazz, Bundle bundle) {Intent intent = new Intent (this, clazz); if (null! = Bundle) {intent. putExtras (bundle);} startActivity (intent);}/*** jump to another activity and end the current ** @ param clazz */protected void goThenKill (Class Clazz) {Intent intent = new Intent (this, clazz); startActivity (intent); finish () ;}/ *** jump to another activity and end, and pass the parameter ** @ param clazz * @ param bundle */protected void goThenKill (Class Clazz, Bundle bundle) {Intent intent = new Intent (this, clazz); if (null! = Bundle) {intent. putExtras (bundle);} startActivity (intent); finish ();}/*** starts an activity, and wait for the returned result ** @ param clazz * @ param requestCode */protected void goForResult (Class Clazz, int requestCode) {Intent intent = new Intent (this, clazz); startActivityForResult (intent, requestCode);}/*** starts an activity and waits for the returned result, and pass the parameter ** @ param clazz * @ param requestCode * @ param bundle */protected void goForResult (Class Clazz, int requestCode, Bundle bundle) {Intent intent = new Intent (this, clazz); if (null! = Bundle) {intent. putExtras (bundle);} startActivityForResult (intent, requestCode );} /*************************************** *********************************** * *****/@ Override public boolean dispatchTouchEvent (MotionEvent ev) {if (ev. getAction () = MotionEvent. ACTION_DOWN) {android. view. view v = getCurrentFocus (); if (isShouldHideInput (v, ev) {InputMethodManager imm = (InputMethod Manager) getSystemService (Context. INPUT_METHOD_SERVICE); if (imm! = Null) {imm. hideSoftInputFromWindow (v. getWindowToken (), 0) ;}} return super. dispatchTouchEvent (ev);} if (getWindow (). superDispatchTouchEvent (ev) {return true;} return onTouchEvent (ev);} private boolean isShouldHideInput (android. view. view v, MotionEvent event) {if (v! = Null & (v instanceof EditText) {int [] location = {0, 0}; v. getLocationOnScreen (location); int left = location [0]; int top = location [1]; if (event. getX () <left | (event. getX ()> left + v. getWidth () | event. getY () <top | (event. getY ()> top + v. getHeight () {return true;} else {return false;}/*** set layout id */protected abstract int setLayoutId (); /*** Initialize all la S */protected abstract void initView ();/*** Initialize all event Events */protected abstract void initEvents ();}