简体   繁体   English

Android:从单独的类文件中调用AsyncTask内部类

[英]Android: Call AsyncTask inner class from a separate Class File

I have a Class: TabsPagerFragmentActivity which hosts all of the tabs. 我有一个Class:TabsPagerFragmentActivity,它托管所有选项卡。

I then have a separate class: ShopsFragment which has an inner class which extends AsyncTask 然后我有一个单独的类:ShopsFragment,它有一个扩展AsyncTask的内部类

I'm trying to call the .execute method on this inner class from the TabsPagerFragmentActivity however i'm getting a 我试图从TabsPagerFragmentActivity调用此内部类的.execute方法但是我得到了一个

 No enclosing instance of the type is accessible error.

Is there a way to call this inner class execute from the TabsPagerFragmentActivity? 有没有办法从TabsPagerFragmentActivity调用此内部类执行? Basically i'm trying to change an image as soon as the user leaves this fragment. 基本上我只是在用户离开这个片段时尝试更改图像。

Code: 码:

public class AlternateImageView extends AsyncTask<String,Integer,Void>{

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

            return null;
        }

        @Override 
        protected void onProgressUpdate(Integer... progress) {

        }

        @Override
        protected void onPostExecute(Void v) {
                       //Do something 
                }
         }

Thanks 谢谢

Something like this? 像这样的东西?

AlternateImageView alternateImageView = new TabsPagerFragmentActivity().new AlternateImageView();
alternateImageView.execute();

I would like to add that I'm not going to pass judgement on this as a good or bad idea. 我想补充一点,我不打算将此判断为一个好的或坏的想法。

This is how to declare your inner class: 这是如何声明你的内部类:

public class AlternateImageView extends AsyncTask<String,Integer,Void>

To use this class from a different class file, you need to add the word static, as the following: 要从其他类文件中使用此类,您需要添加单词static,如下所示:

public static class AlternateImageView extends AsyncTask<String,Integer,Void>

Then you can use your class like this: 然后你可以像这样使用你的类:

AlternateImageView task = new TabsPagerFragmentActivity.AlternateImageView();
task.execute();

Change 更改

public class 

to

public static class

Declare your AsyncTask as a static class. 将AsyncTask声明为静态类。 A static inner class makes the class be treated on the same visibility of other classes at the top level of the package, but you get the organizational benefits of having it as an inner class. 静态内部类使得类在包的顶层与其他类的相同可见性处理,但是您可以获得将其作为内部类的组织好处。 For example: 例如:

Class1
Class2
Class3
    >Inner1
Class4

To call Inner1 you would need to do new Class3().new Inner1() . 要调用Inner1,您需要执行new Class3().new Inner1() If you make it static like this: 如果你像这样静态:

Class1
Class2
Class3
    >static Inner1
Class4

Then you can create it as you would any other class in the package like new Inner1() 然后你可以像创建new Inner1()那样创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM