簡體   English   中英

評論我對Android的MVP模式

[英]Comments on my MVP pattern for Android

我計划在我的新Android項目中使用MVP模式。 我已經做了一些示例代碼,我想知道,我是否正確實現了它? 請對代碼發表評論並發布您的建議。

我的活動類我從我的BaseView類擴展它,我正在實現一個接口。 此活動只是在新線程中調用Web服務並更新textview中的值。

public class CougarTestView extends BaseView implements ICougarView,
        OnClickListener {
    CougarTestPresenter _presenter;
    public String activityName = "CougarHome";

    /** Called when the activity is first created. */`enter code here`
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, activityName);
        setContentView(R.layout.main);
        _presenter = new CougarTestPresenter(this);
        getSubmitBtn().setOnClickListener(this);
        getCallInfoBtn().setOnClickListener(this);

    }

    private Button getCallInfoBtn() {
        return (Button) findViewById(R.id.btn_callinfo);
    }

    public void setServiceValue(String retVal) {
        // TODO Auto-generated method stub
        getResultLabel().setText(retVal);
        setPbar(false);
        // toastMsg(retVal);
    }

    public void ResetPbar() {
        getProgressBtn().setProgress(0);
    }

    public void setProcessProgress(int progress) {

        if (getProgressBtn().getProgress() < 100) {
            getProgressBtn().incrementProgressBy(progress);
        } else {
            setPbar(false);
        }
    }

    private TextView getResultLabel() {
        return (TextView) findViewById(R.id.result);
    }

    private Button getSubmitBtn() {
        return (Button) findViewById(R.id.btn_triptype);
    }

    private ProgressBar getProgressBtn() {
        return (ProgressBar) findViewById(R.id.pgs_br);
    }

    public void setPbar(boolean visible) {
        if (!visible) {
            getProgressBtn().setVisibility(View.GONE);
        } else
            getProgressBtn().setVisibility(View.VISIBLE);
    }

    @Override
    public void setHttpResult(String retVal) {
        // TODO Auto-generated method stub
        setServiceValue(retVal);
    }

    private void toastMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_triptype: {           
            try {
                _presenter.valueFromService(RequestType.CallInfo, 0);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;
        }

        default:
            setServiceValue("default");
        }
    }


}

我的活動課:在我的活動課中,我有一個文本視圖和一個按鈕。 當我按下按鈕時,它會調用web服務來獲取演示者類中的數據。 presenter類調用webservice解析響應並在活動的textview中設置值。

My presenter class


public class CougarTestPresenter {
    ICougarView mIci;
    RequestType mRtype;
    public String result= "thisi s result i";
    Handler mHandle;


    public CougarTestPresenter(ICougarView ici) {
        mIci = ici; 

    }
    public void valueFromService(RequestType type, int x) throws Exception{
        String url = getURLByType(type);

        // GetServiceresult service = new GetServiceresult();
        // service.execute(url);
        Handler handle = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {

                case Globals.IO_EXPECTION: {
                    Toast.makeText(mIci.getContext(), msg.toString(),
                            Toast.LENGTH_LONG).show();
                    NetworkConnectivityListener connectivityListener = NetworkConnectivityListener
                            .getInstace();
                    mHandle = CustomHandler.getInstance(mIci.getContext(),
                            connectivityListener, mIci);
                    connectivityListener.registerHandler(mHandle,
                            Globals.CONNECTIVITY_MSG);
                    connectivityListener.startListening(mIci.getContext());
                    mIci.setPbar(false);
                }
                    break;
                case Globals.RHAPSODY_EXCEPTION:{   
                    ExceptionInfo exInfo =null;
                        try {
                            exInfo = Utility.ParseExceptionData(msg.obj.toString());

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }                       
                        mIci.setServiceValue(exInfo.Message + exInfo.Type +exInfo.Detail);

                //      new HandleRhapsodyException(mIsa, exInfo);
                }
                break;
                default: {
                    Toast.makeText(mIci.getContext(), msg.toString(),
                            Toast.LENGTH_LONG).show();
                    mIci.setServiceValue(msg.obj.toString());
                }
                }

            }
        };

        ServiceResult thread = new ServiceResult(handle, url);
        mIci.setPbar(true);
        thread.start();

    }

    public String getURLByType(RequestType type) {
        // TODO Auto-generated method stub
        switch (type) {
        case CallInfo: {
            return ("www.gmail.com");
        }
        case TripType: {
            return ("www.google.com");
        }
        default:
            return ("www.cnet.com");

        }
    }

    private class ServiceResult extends Thread {
        Handler handle;
        String url;

        public ServiceResult(Handler handle, String url) {
            this.handle = handle;
            this.url = url;
        }

        public void run() {
            sendExceptionLog(handle);

        }
    }

    public void sendExceptionLog(Handler handle) {

        DebugHttpClient httpClient = new DebugHttpClient();

        HttpGet get = new HttpGet(
                "https://192.168.194.141/TripService/service1/");
        try {
            HttpResponse response = httpClient.execute(get);

            HttpEntity r_entity = response.getEntity();
            String xmlString = EntityUtils.toString(r_entity);
            // setdvrid.setText(xmlString + " "
            // + response.getStatusLine().getStatusCode());

            httpClient.getConnectionManager().shutdown();

            if (response.getStatusLine().getStatusCode() != 200) {
                handle.sendMessage(Message.obtain(handle, Globals.RHAPSODY_EXCEPTION,
                        xmlString));
            result= Utility.ParseExceptionData(xmlString).Message;
            }
            else
            {
                handle.sendMessage(Message.obtain(handle, Globals.SERVICE_REPONSE,
                        response.getStatusLine().getStatusCode()
                                + response.getStatusLine().getReasonPhrase()
                                + xmlString));
            }

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION,
                    e.getMessage().toString() + "she"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            handle.sendMessage(Message.obtain(handle, Globals.IO_EXPECTION, e
                    .getMessage().toString() + "he"));
        } catch (Exception e) {
            handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION,
                    e.getMessage().toString() + "it"));
        }

    }

下面的接口在activity類中實現,activity類的實例作為接口對象發送到presenter類的構造函數。

my view interface

public interface ICougarView {
public void setServiceValue(String retVal);
public void setProcessProgress(int progress);
public void setPbar(boolean b);
public void ResetPbar();
public Context getContext();
}

對不起已經晚了:)我已經在Android上使用MVP了。

活動是主持人。 每個演示者都有一個模型鏈接(有時是服務,有時不是,取決於任務)和視圖。 我創建自定義視圖並將其設置為活動的內容視圖。

看到:

public class ExampleModel {
   private ExampleActivity presenter;

   public ExampleModel(ExampleActivity presenter) {
       this.presenter = presenter;
   }
   //domain logic and so on
}

public class ExampleActivity extends Activity {
   private ExampleModel model;
   private ExampleView view;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       model = new ExampleModel(this);
       view = new ExampleView(this);
       setContentView(view);
   }
   // different presenter methods
}

public class ExampleView extends LinearLayout {

    public ExampleView(Context context) {
        super(context);
    }
}

另外,我在這里討論過這個話題。

我應警告你,不應將活動視為觀點。 當我們使用PureMVC編寫將Activity視為視圖組件時,我們對它的了解非常糟糕。 Activity非常適合控制器/演示者/視圖模型(我已經嘗試了所有這些,我最喜歡MVP),它具有很好的管理視圖(視圖,對話等)的工具,而它本身不是視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM