Android浅談MVPモード1

16300 ワード

最近MVPモードを勉强した心得をずっと记录したいと思っていますが、书くのが下手で、仕方がないので、先に书いてからすぐに更新します.私はいくつかのコードを貼り付けて、MVPモードの理解に対してコードの中で詳しく注釈することができます
例1:フラッシュ画面でログインしたかどうかを判断する
/**
 * MVP    : MVP Activity/fragment  View ,      View   ,  Activity/fragment  View  
 * P        Presenter     ,   PresenterImpl     /  
 *  Activity/fragment        p,  new SplashPresenter     ,  new SplashPresenter  ,
 * P       Activity/fragment     ,     “this”,(PresenterImpl   Presenter    )
 *   p        ,xxView(       ,    xxView    ,   xxActivity    )
 * Activity/fragment             View  ,        PresenterImpl , Activity/fragment      
 * 

* View: View , View , 。 * Android Activity Fragment View 。View UI *

* Model: Model 。 MVC Model, 。 * MVP Model , , 。 *

* Presenter: Presenter View Model 。 * MVP Model View 。 Presenter Model , * View 。 Presenter View Model , * View Model , View 。 */ //View public class SplashActivity extends BaseActivity implements SplashView { private static final long DURATION = 2000; private SplashPresenter mSplashPresenter; @InjectView(R.id.iv_splash) ImageView mIvSplash; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); ButterKnife.inject(this); //TODO /** * Activity/fragment p , new SplashPresenter , new SplashPresenter */ mSplashPresenter = new SplashPresenterImpl(this); /** * 1. P * 2. , MainActivity view * 3. 2 ( ), LoginActivity view */ mSplashPresenter.checkLogined(); } //Activity/fragment View , PresenterImpl , Activity/fragment @Override public void onCheckedLogin(boolean isLogined) { if (isLogined) { // Activity MainActivity.class : ,true : finish startActivity(MainActivity.class, true); } else { // 2 ( ), LoginActivity ObjectAnimator alpha = ObjectAnimator.ofFloat(mIvSplash, "alpha", 0, 1).setDuration(DURATION); alpha.start(); // , , handler alpha.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); startActivity(LoginActivity.class, true); } }); } } }

/**
 *   : itheima
 *   :2016-10-15 10:50
 *   :http://www.itheima.com
 *       ,xxView(       ,    xxView    ,   xxActivity    )
 */

public interface SplashView {

    void onCheckedLogin(boolean isLogined);
}

P層:
/**
 *   : itheima
 *   :2016-10-15 10:50
 *   :http://www.itheima.com
 * P        Presenter     ,   PresenterImpl     /  
 */
//      Presenter     
public interface SplashPresenter {
    void checkLogined();
}
/**
 *   : itheima
 *   :2016-10-15 10:51
 *   :http://www.itheima.com
 * P        Presenter     ,   PresenterImpl     /  
 */

public class SplashPresenterImpl implements SplashPresenter {

    //  p        ,xxView(       ,    xxView    ,   xxActivity    )
    private SplashView mSplashView;

    public SplashPresenterImpl(SplashView splashView) {
        mSplashView = splashView;
    }

    //   PresenterImpl     /  
    @Override
    public void checkLogined() {
        if (EMClient.getInstance().isLoggedInBefore() && EMClient.getInstance().isConnected()) {
            //      
            mSplashView.onCheckedLogin(true);
        } else {
            //    
            mSplashView.onCheckedLogin(false);
        }

    }
}

例2:ユーザーのログインが成功したかどうか、アカウントとパスワードを保存する
Viewレイヤ:
public class LoginActivity extends BaseActivity implements TextView.OnEditorActionListener ,LoginView{

    private static final int REQUEST_SDCARD = 1;

    @InjectView(R.id.et_username)
    EditText mEtUsername;
    @InjectView(R.id.til_username)
    TextInputLayout mTilUsername;
    @InjectView(R.id.et_pwd)
    EditText mEtPwd;
    @InjectView(R.id.til_pwd)
    TextInputLayout mTilPwd;
    @InjectView(R.id.btn_login)
    Button mBtnLogin;
    @InjectView(R.id.tv_newuser)
    TextView mTvNewuser;

    private LoginPresenter mLoginPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        /**
         *      
         */
        mEtUsername.setText(getUserName());
        mEtPwd.setText(getPwd());
        mEtPwd.setOnEditorActionListener(this);

        mLoginPresenter = new LoginPresenterImpl(this);
    }

    /**
     *    startActivity   ,    Intent  
     *             singleTask,  singleTop           
     * @param intent
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mEtUsername.setText(getUserName());
        mEtPwd.setText(getPwd());
    }

    @OnClick({R.id.btn_login, R.id.tv_newuser})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.tv_newuser:
            startActivity(RegistActivity.class,false);

                break;
        }
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (v.getId()==R.id.et_pwd){
            if (actionId== EditorInfo.IME_ACTION_DONE){
                login();
            }
        }
        return false;
    }

    private void login() {
        String username = mEtUsername.getText().toString().trim();
        String pwd = mEtPwd.getText().toString().trim();

        if (!StringUtils.checkUsername(username)){
            mTilUsername.setErrorEnabled(true);
            mTilUsername.setError("      ");

            mEtUsername.requestFocus(View.FOCUS_RIGHT);

            return;
        }else {
            mTilUsername.setErrorEnabled(false);
        }
        if (!StringUtils.checkPwd(pwd)){
            mTilPwd.setErrorEnabled(true);
            mTilPwd.setError("     ");

            mEtPwd.requestFocus(View.FOCUS_RIGHT);
            return;
        }else{
            mTilPwd.setErrorEnabled(false);
        }
        /**
         * 1.       
         */
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PermissionChecker.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_SDCARD);
            return;
        }

        showDialog("       ...");

        mLoginPresenter.login(username,pwd);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==REQUEST_SDCARD){
            if (grantResults[0]==PermissionChecker.PERMISSION_GRANTED){
                //    
                login();
            }else{
                showToast("         ,     ");
            }
        }
    }

    @Override
    public void onLogin(String username, String pwd, boolean success, String msg) {
        hideDialog();
        if (success){
            /**
             * 1.    
             * 2.       
             */
            saveUser(username, pwd);
            startActivity(MainActivity.class,true);
        }else {
            /**
             * 1.Toast
             */
            showToast("     :"+msg);
        }
    }
}
/**
 *   : itheima
 *   :2016-10-15 17:13
 *   :http://www.itheima.com
 */
public interface LoginView {
    void onLogin(String username,String pwd,boolean success,String msg);
}

P層:Pでビジネス層Presenterで定義された機能を作成し、クラスPresenterImplでの操作機能/論理を実現する
/**
 *   : itheima
 *   :2016-10-15 17:13
 *   :http://www.itheima.com
 */
public interface LoginPresenter {
    void login(String username,String pwd);
}

 
/**
 *   : itheima
 *   :2016-10-15 17:14
 *   :http://www.itheima.com
 */
public class LoginPresenterImpl implements LoginPresenter {
    private LoginView mLoginView;

    public LoginPresenterImpl(LoginView loginView) {
        mLoginView = loginView;
    }

    @Override
    public void login(final String username, final String pwd) {

        //    (3.5.x)                 
        EMClient.getInstance().login(username, pwd, new CallBackListener() {
            @Override
            public void onMainSuccess() {
                mLoginView.onLogin(username,pwd,true,null);
            }

            @Override
            public void onMainError(int i, String s) {
                mLoginView.onLogin(username,pwd,false,s);
            }
        });
    }
}

例3:登録が成功したかどうか、アカウントパスワードを保存してログインページに入り、失敗トースト
Viewレイヤ:
public class RegistActivity extends BaseActivity implements TextView.OnEditorActionListener, RegistView {

    @InjectView(R.id.et_username)
    EditText mEtUsername;
    @InjectView(R.id.til_username)
    TextInputLayout mTilUsername;
    @InjectView(R.id.et_pwd)
    EditText mEtPwd;
    @InjectView(R.id.til_pwd)
    TextInputLayout mTilPwd;
    @InjectView(R.id.btn_regist)
    Button mBtnRegist;

    private RegistPresenter mRegistPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
        }


        setContentView(R.layout.activity_regist);
        ButterKnife.inject(this);
        mRegistPresenter = new RegistPresenterImpl(this);
        // UI    
        mEtPwd.setOnEditorActionListener(this);
    }

    @OnClick(R.id.btn_regist)
    public void onClick() {
        regist();
    }

    private void regist() {
        String username = mEtUsername.getText().toString().trim();
        String pwd = mEtPwd.getText().toString().trim();

        if (!StringUtils.checkUsername(username)){
            mTilUsername.setErrorEnabled(true);
            mTilUsername.setError("      ");

            mEtUsername.requestFocus(View.FOCUS_RIGHT);

            return;
        }else {
            mTilUsername.setErrorEnabled(false);
        }
        if (!StringUtils.checkPwd(pwd)){
            mTilPwd.setErrorEnabled(true);
            mTilPwd.setError("     ");

            mEtPwd.requestFocus(View.FOCUS_RIGHT);
            return;
        }else{
            mTilPwd.setErrorEnabled(false);
        }
        showDialog("    ...");
        mRegistPresenter.regist(username,pwd);
    }
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (v.getId() == R.id.et_pwd) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                regist();
                return true;
            }
        }
        return false;
    }

    @Override
    public void onRegist(String username, String pwd, boolean isSuccess, String msg) {
        hideDialog();
        if (isSuccess){
            /**
             *              
             *        
             */
            saveUser(username, pwd);

            startActivity(LoginActivity.class,true);
        }else {
            /**
             *    ,       
             */
            showToast("    :"+msg);
        }
    }
}
/**
 *   : itheima
 *   :2016-10-15 11:49
 *   :http://www.itheima.com
 */

public interface RegistView {

    void onRegist(String username,String pwd,boolean isSuccess,String msg);
}

P層:
/**
 *   : itheima
 *   :2016-10-15 11:47
 *   :http://www.itheima.com
 */

public interface RegistPresenter {
    void regist(String username,String pwd);
}
/**
 *   : itheima
 *   :2016-10-15 11:48
 *   :http://www.itheima.com
 */

public class RegistPresenterImpl implements RegistPresenter {

    private RegistView mRegistView;

    public RegistPresenterImpl(RegistView registView) {
        mRegistView = registView;
    }

    @Override
    public void regist(final String username, final String pwd) {
        /**
         * 1.    Bmob    
         * 2.   Bmob           
         * 3.   Bmob   ,     ,    Bmob        
         */
        User user = new User();
        user.setPassword(pwd);
        user.setUsername(username);

        user.signUp(new SaveListener() {
            //Bmob                 
            @Override
            public void done(final User user, BmobException e) {
                if (e==null){
                    //new Thread。。。new           ,         
                    //        ,      new  

                    //           
                    ThreadUtils.runOnSubThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                EMClient.getInstance().createAccount(username, pwd);
                                //             
                                ThreadUtils.runOnMainThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mRegistView.onRegist(username,pwd,true,null);
                                    }
                                });
                            } catch (final HyphenateException e1) {
                                e1.printStackTrace();
                                // Bmob    user    
                                user.delete();
                                //       
                                ThreadUtils.runOnMainThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mRegistView.onRegist(username,pwd,false,e1.toString());
                                    }
                                });
                            }
                        }
                    });
                }else {
                    //   ,     Activity
                    mRegistView.onRegist(username,pwd,false,e.getMessage());
                }
            }
        });

    }
}

また、いくつかの資料も参考にしました.http://chuansong.me/n/632293551521
http://chuansong.me/n/2271649851831
あなたの役に立つことを望みます