android - 对我的 Android MVP 模式的评论

标签 android mvp

我计划在我的新 Android 项目中使用 MVP 模式。我已经完成了一些示例代码,我想知道,我是否正确地实现了它?请对代码提出意见并发表您的建议。

我的 Activity 类 我正在从我的 BaseView 类中扩展它,并且我正在实现一个接口(interface)。此 Activity 只是在新线程中调用网络服务并更新 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");
        }
    }


}

我的 Activity 课:在我的 Activity 课中,我有一个 TextView 和一个按钮。当我按下按钮时,它会调用网络服务来获取演示者类中的数据。 Presenter 类调用 Web 服务解析响应并在 Activity 的 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"));
        }

    }

下面的接口(interface)在 Activity 类中实现, Activity 类的实例作为接口(interface)对象发送给演示者类的构造函数。

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。

Activity 是演示者。每个演示者都有一个指向模型(有时是服务,有时不是,取决于任务)和 View 的链接。我创建自定义 View 并将其设置为 Activity 的内容 View 。

参见:

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);
    }
}

此外,我已经讨论了这个话题 here .

我应该警告您,不应将 Activity 视为 View 。当我们使用将 Activity 视为 View 组件的 PureMVC 编写时,我们对它的体验非常糟糕。 Activity 非常适合 Controller /演示者/ View 模型(我已经尝试过所有这些,我最喜欢 MVP),它具有用于管理 View ( View 、对话框等)的出色工具,但它本身不是 View 。

关于android - 对我的 Android MVP 模式的评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7519163/

相关文章:

Android: Realm + Retrofit - 序列化apiresponse

android - 撰写 LazyColumn 选择一项

java - setOnItemClickListener 和 onItemClick 有什么区别

c# - MVP 和 Presenter 粒度

c# - 关于 model-view-presenter (C#) 的一般性问题,模型应该知道 presenter 吗?

android - 在 MVP 模式中将 View 的引用传递给 Presenter 是一种不好的做法吗?

android - 在 ViewPager 上 float ViewPagerIndicator

java - 搜索通过接口(interface)进行类绑定(bind)的示例

java - 我应该在哪里进行改造操作?

android - paypal 集成到 android 应用程序给出错误?