使用相同的AsyncTask更新不同的看法 [英] Use the same AsyncTask to update different views

查看:127
本文介绍了使用相同的AsyncTask更新不同的看法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有6个不同的活动按钮。单击该按钮的功能几乎根据活动不同PARAMS相同的任务。

I have a button on 6 different Activities. Clicking on that button does almost the same task with different params depending on the Activity.

这将使用来完成的的AsyncTask onPostExecute()按钮状态将被改变。

This will be done using an AsyncTask and in onPostExecute() the button state will be changed.

someButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        new Task().execute("param1", "param2");
    }
}

private class Task extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //background task using params[0], params[1]
        return "success" or "error";
    }

    @Override
    protected void onPostExecute(String result) {

        if (result == "success") {
            //change the someButton state
        }else{
            //show an error message
        }
}

而不必在所有的6项活动相同的AsyncTask的,我怎么可以用一个单一的AsyncTask从所有的活动,改变各自的看法?的

Instead of having the same AsyncTask in all the 6 Activities, how can I use a single Asynctask from all the Activities and change the respective view?

推荐答案

您应该创建任务,与方法的onSuccess,onFailure处并覆盖它们。

You should create Task, with methods onSuccess, onFailure and override them.

public class Task extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {

        //background task using params[0], params[1]
        return "success" or "error";
    }

    @Override
    protected void onPostExecute(String result) {

        if (result == "success") {
            onSuccess(result);
        }else{
            onFailure(result);
        }
    }

    protected void onSuccess(String result) {};
    protected void onFailure(String result) {};
}

,然后在活动中使用这样的:

and then in activity use it like this:

someButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        new Task(){
            @Override
            protected void onSuccess(String result){
                // do what you want
            }
            @Override
            protected void onFailure(String result){
                // do what you want
            }
        }.execute("param1", "param2");
    }
}

这篇关于使用相同的AsyncTask更新不同的看法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆