如何使用上下文访问/操纵另一个类/活动 [英] How to use Context to access/manipulate another class/activity

查看:131
本文介绍了如何使用上下文访问/操纵另一个类/活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创造,我的所有活动中使用/份额从URL下载内容的通用AsynceTask类。因为这个原因,我不希望OnPostExecute做以外的任何其他的内容发送回在调用的AsyncTask类活动的一些方法。

I want to create a generic AsynceTask class that all my activities use/share for downloading content from a url. for this reason, I don't want the OnPostExecute to do anything other than to send the content back to some method in the activity that invoked the AsyncTask class.

我知道,我需要创建一个构造函数,设置调用该的AsyncTask ,但后来什么,我怎么使用上下文来送东西的活动的背景下背对应于该上下文的活性。我见过的任何教程,说明如何以这种方式使用环境。

I know that I need to create a constructor that sets the context of the Activity that invoked the AsyncTask, but then what, how do I use the context to send something back the the activity corresponding to that context. I've seen no tutorials that show how to use context in this manner.

可以说我有:

public class LoginActivity {

    public int ActivityMember;

    public void HandleButtonClick(void){
        DownloadFromURL task = new DownloadFromURL(this);
        task.execute(url);
    }

    public void HandleLoginResult(int x){
        ActivityMember = x;
    }
}

现在在一个单独的Java文件我有:

now in a separate java file I have:

    private class DownloadFromURL extends AsyncTask<List<NameValuePair>, Long, JSONObject> {
Context context;

    public void DownloadFromURL (Context context){
        this.context = context;
    }

    @Override
    protected void onPostExecute(JSONObject json) {
         context.(<- *my question involves this part of code)
    }
}

我是pretty确保我不能叫 context.ActivityMember context.HandleLoginResult(Y) onPostExecute ,因为上下文的类型没有 LoginActivity ,它的上下文。
所以,我怎么能访问成员或属于 LoginActivity 方法,使用它的上下文?

I'm pretty sure I cant call context.ActivityMember, or context.HandleLoginResult(y) inside onPostExecute, because context is not of the type LoginActivity, its a Context. So how can I access members or methods belonging to LoginActivity, using it's context?

推荐答案

您可以使用((ActivityName)CONTEXTNAME).methodName()

但它不是一个很好的解决方案。你可以尝试像

But it is not a good solution. You can try something like this

这篇关于如何使用上下文访问/操纵另一个类/活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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