从片段中的ActivityMain中调用AsyncTask方法

问题描述 投票:0回答:2

以前我在主要活动中使用过AsyncTask并用:

new SyncGetLocations(ActivityMain.this).execute();

现在,我将其移到一个片段上,现在不知道如何从MainActivity中调用它。

AsyncTask看起来很相似:

private static class SyncGetLocations extends AsyncTask<Void, Void, Void> {

    private WeakReference<ActivityMap> activityReference;

    SyncGetLocations(ActivityMap context) {
        activityReference = new WeakReference<>(context);
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected Void doInBackground(Void... voids) {
    }

    @Override
    protected void onPostExecute(Void aVoid) {

    }

}

android android-asynctask fragment
2个回答
0
投票

Either >>

从MainActivity找到您的片段:

val fragment = getSupportFragmentManager()。findFragmentByTag(...)或findFragmentByID(...)

然后在此片段中调用方法以启动asyncTask

fragent.callAsyncTask()

公开您的asynctask或将其从fragment中删除为自己的类,并在任何需要的地方调用它

[我建议您使asyntask不再是您想从任何地方调用它的活动片段的内部类


0
投票

尝试使用类似方法将侦听器附加到片段上>

public interface FragmentInteractionListener{ 
void onClick(); 
© www.soinside.com 2019 - 2024. All rights reserved.