调用Fragment类'方法的问题

时间:2013-12-13 10:40:05

标签: android android-fragments

我有一个“HomeActivity”课程,如下:

        public class HomeActivity extends FragmentActivity implements OnClickListener {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                FragmentManager fm = getSupportFragmentManager();

                // Create the list fragment and add it as our sole content.
                if (fm.findFragmentById(android.R.id.content) == null) {
                    HomeFragment list = new HomeFragment();
                    fm.beginTransaction().add(android.R.id.content, list).commit();

                }
            }
        public static class HomeFragment extends Fragment {

        webServiceTask = WebServiceTask.getInstance(
                                    getActivity(), Constants.METHOD_NAME_PRODUCTS,
                                    Constants.PRODUCT_NAME, null);

public  void Work() {}
    }
    }

我有另一个类WebServiceTask,如下所示:

  final public class WebServiceTask extends AsyncTask<String, String, String> {
    private WebServiceTask(final Activity activity, final String methodName,
                final String productName, final String addInfo[]) {
            super();
            this.activity = activity;
            this.methodName = methodName;
            this.productName = productName;
            this.addInfo = addInfo;
        }
public static WebServiceTask getInstance(final Activity activity,
            final String methodName, final String productName,
            final String additionalInfo[]) {
        webServiceTask = new WebServiceTask(activity, methodName, productName,
                additionalInfo);
        return webServiceTask;
    }
    protected void onPostExecute() {

    // Here I am trying to call the work() method in HomeFragment, How can I do that?
    }

我的问题是如何从onPostExecute()调用HomeFragment类中的work()方法。

4 个答案:

答案 0 :(得分:1)

我建议为你创建一个监听器,并在post执行中调用它的方法。它将为您提供更多的灵活性和控制权,使您可以完成任务。以下是我将使用的示例代码:

public class MyTask extend AsyncTask<Void, Void, Boolean> {

    public interface MyTaskListener {
         void onSuccess();
         void onFailure();
         void onError(Throwable t);
    }

    private Throwable error;
    private MyTaskListener listener;


    public MyTask(MyTaskListener listener) {
          this.listener = listener;
    }

    @Overrride
    public Boolean doInBackground(Void... params) {

        try {
            if (workCompleted()) { 
                //work completed without error - return true
                return Boolean.TRUE;
            } else {
                //work failed to complete - return false
                return Boolean.FALSE;
            }
        } catch(Exception e) {
            //unexpected error  happened - remember error and return null
            this.error = e;
            return null;
        }  


    }


    @Override
    public void onPostExecute(Boolean result){
         if (!isCancelled()) { //you only want to process if task wasn't cancelled

             if (this.error != null && result == null) { //we have error, process it
                 if (listener != null) {
                     listener.onError(this.error);
                 }
             }

             if (Boolean.FALSE.equals(result)) { //we have faile, process it
                 if (listener != null) {
                     listener.onFail();
                 }
             }

             if (Boolean.TRUE.equals(result)) { //we have success
                 if (listener != null) {
                     listener.onSuccess();
                 }
             }


         }
    }


}

然后,在你的activit / fragment / service /中使用这样的东西:

public class MyActivity extends Activity {


    private void someInstanceMethod() {/ *do your work here */}

    @Override
    public void onCreate(Bundle savedInstanceState) {

          //setup ui, or do whatever you need

          //create MyAsyncTask with proper listener
          MyAsyncTask task = new MyAsyncTask(new MyAsyncTask.MyAsyncTaskListener() {

              @Override
              public void onSuccess() {
                  //call your instance method here
                  someInstanceMethod();

              }

              @Override
              public void onFailure() {
                  //process fail
              }

              @Override
              public void onError() {
                  //process error
              }


          });



    } 

}

答案 1 :(得分:0)

这是一种方法。我不知道它是否是最好的一个:

将工作功能设为公共静态 void。从Asynctask onpostexecute中调用它为

HomeActivity.Work(); 

编辑: 还有一种方式(再次不确定这是否是最佳方式)

如果您无法完成这项工作,请考虑将您的asynctask类放在家庭活动类

答案 2 :(得分:0)

使用FragmentManger findFragmentById()findFragmentByTag()您可以获取当前片段的实例并调用您的片段方法。

答案 3 :(得分:0)

创建接口文件

public interface AsynAction
{
  public void Work();
}

在HomeActivity中实现AsynAction

public class HomeActivity extends FragmentActivity implements OnClickListener,AsyncAction {

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                FragmentManager fm = getSupportFragmentManager();

                // Create the list fragment and add it as our sole content.
                if (fm.findFragmentById(android.R.id.content) == null) {
                    HomeFragment list = new HomeFragment();
                    fm.beginTransaction().add(android.R.id.content, list).commit();

                }
            }
        public static class HomeFragment extends Fragment {

        webServiceTask = WebServiceTask.getInstance(
                                    getActivity(), Constants.METHOD_NAME_PRODUCTS,
                                    Constants.PRODUCT_NAME, null);
@Override
public  void Work() 
          {
          }
    }
    }

然后在您的asynctask中进行更改以接收asyncAction对象作为参考

final public class WebServiceTask extends AsyncTask<String, String, String> {
    private WebServiceTask(final AyscAction asycAction,final Activity activity, final String methodName,
                final String productName, final String addInfo[]) {
            super();
            this.activity = activity;
            this.asycAction=asycAction;
            this.methodName = methodName;
            this.productName = productName;
            this.addInfo = addInfo;
        }
public static WebServiceTask getInstance(final AyscAction asycAction,final Activity activity,
            final String methodName, final String productName,
            final String additionalInfo[]) {
        webServiceTask = new WebServiceTask(asycAction,activity, methodName, productName,
                additionalInfo);
        return webServiceTask;
    }
    protected void onPostExecute() {

    // You can call work from here
       if(asynAction!=null)
          asyncAction.Work();
    }