MVP

本文深入解析MVP(Model-View-Presenter)模式在Android应用开发中的应用。通过实例讲解如何通过接口回调实现数据传递,解决多线程下UI更新的问题。探讨了Presenter、View和Model的角色与交互,以及异步请求数据的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个重要知识就是通过接口回调实现数据的传递

结构:
在这里插入图片描述

view模型c

在视图这里可能会报这个错误Only the original thread that created a view hierarchy can touch its views.,
此时你需要handle来更新视图,你有其他方法也行


public class MVPActivity extends AppCompatActivity implements ViewInterface {

    private Button button;
    private EditText editText;
    private TextView textView;
    private MvpPresenter presenter;
    private String data;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 2:
                {
                    textView.setText(data);
                }break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mvp);
        initView();
        setLisenter();
        presenter = new MvpPresenter(this);
    }

    private void initView() {
        button = findViewById(R.id.bt_mvp);
        editText = findViewById(R.id.et_mvp);
        textView = findViewById(R.id.tv_mvp);
    }

    private void setLisenter() {
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String city = String.valueOf(editText.getText());
                if (TextUtils.isEmpty(city)){
                    city="北京";
                }

                presenter.getWeather(city);
            }
        });
    }

    @Override
    public void updateWeather(String resData) {
        data = resData;
        Message message = new Message();
        message.what=2;
        handler.sendMessage(message);
    }
}

重要的接口实现
视图接口回调,需要activity实现

public interface ViewInterface {
    void updateWeather(String data);
}

Presenter模型

**需要一个视图接口和一个模型接口,在这里模型是使用了静态方法调用,差不多


public class MvpPresenter {
    private static final String TAG="AAA";

    private ViewInterface viewInterface;

    public MvpPresenter(ViewInterface viewInterface) {
        this.viewInterface = viewInterface;
    }

    public void getWeather(String city){

        Log.d(TAG, "getWeather: MvpPresenter"+city);
        Model.getWeather(city, new ModelCallback() {

            @Override
            public void onSuccess(String resData) {
                viewInterface.updateWeather(resData);
                Log.d(TAG, "onSuccess: "+resData);
            }

            @Override
            public void onFailure(String errorData) {
                Log.d(TAG, "onFailure: ");
            }

            @Override
            public void onComplete() {
                Log.d(TAG, "onComplete: ");
            }
        });
    }

}


model模型

/**
 * callback是反馈数据给presenter层
 */
public interface ModelCallback {
    /**
     *
     * @param resData 接受到的数据
     */
    void onSuccess(String resData);

    /**
     *
     * @param errorData 返回给上一层的错误信息
     */
    void onFailure(String errorData);

    /**
     *
     */
    void onComplete();
}

public class Model {
    private static final String TAG="AAA";
    private static String data;

    public static void getWeather(final String city,final ModelCallback callback){
        requestWeather(city, callback);
    }

    private static void requestWeather(String city, final ModelCallback callback) {
        OkHttpClient client = new OkHttpClient();
        final Request request = new  Request.Builder()
                .get()
                .url(Comment.BASH_URL+"?city="+city+"&key="+Comment.KEY)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: ");
                callback.onFailure("错误");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    data = response.body().string();
                    Log.d(TAG, "onResponse: "+data);
                    callback.onSuccess(data);
                }
            }
        });
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值