Android的:如何更新从AsyncTask的一个用户界面,如果AsyncTask的是在一个单独的类?的是、在一、用户界面、Android

2023-09-12 04:35:59 作者:兜兜里没糖糖

我讨厌内部类。

我有谁启动一个短寿命主要活动AsyncTask的。

I've a main activity who launches a 'short-life' AsyncTask.

AsyncTask的是在一个单独的文件,不是一个内部类主要活动

AsyncTask is in a separate file, is not an inner class of main activity

我需要异步任务更新,从主要活动一个TextView。

I need async task updates a textView from main Activity.

我知道我可以更新从onProgressUpdate一个TextView,如果AsyncTask的是一个内部类

I know i can update a TextView from onProgressUpdate, if AsyncTask is a inner class

但如何从外部,indipendent,异步任务是什么?

But how from an external, indipendent, async task ?

更新:这看起来像工作:

UPDATE: This looks like working :

在acitivty我调用任务

In acitivty i call the task

backgroundTask = new BackgroundTask(this);
backgroundTask.execute();

在构造函数中,我

public BackgroundTask(Activity myContext)
{
    debug = (TextView) myContext.findViewById(R.id.debugText);
}

在这里的调试是AsyncTask的私人领域。

where debug was a private field of AsyncTask.

所以onProgressUpdate我可以

So onProgressUpdate I can

debug.append(text);

谢谢大家的建议

Thanks for all of you suggestions

推荐答案

AsyncTask的总是从活动单独的类,但我怀疑你的意思是在不同的文件比你活动类文件,所以你不能受益于活动的内部类。只需通过活动上下文参数传递给您的异步任务(即它的构造函数)

AsyncTask is always separate class from Activity, but I suspect you mean it is in different file than your activity class file, so you cannot benefit from being activity's inner class. Simply pass Activity context as argument to your Async Task (i.e. to its constructor)

class MyAsyncTask extends AsyncTask<URL, Integer, Long> {

    Activity mActivity;

    public MyAsyncTask(Activity activity) {
       mActivity = ativity;
    }

 ...

和在需要时使用(记得在不使用doInBackground()),即所以当你通常会叫

and use when you need it (remember to not use in during doInBackground()) i.e. so when you would normally call

int id = findViewById(...)

在异步任务你叫即。

int id = mActivity.findViewById(...);

其中, mActivity 传递活动。请注意,您必须声明为活动mActivity ,而不仅仅是上下文mActivity

where mActivity is passed activity. Please note you need to declare it as Activity mActivity, not just Context mActivity.