简体   繁体   English

让活动知道片段何时完成操作

[英]let activity know when fragment is finished an operation

I have an activity with two fragments. 我的活动有两个片段。

Fragment A does a complex operation during onResume(), and Fragment B needs fragment A to be finished the complex operation, or else user interaction with Fragment B will cause a crash. 片段A在onResume()期间执行复杂的操作,而片段B需要片段A完成复杂的操作,否则用户与片段B的交互将导致崩溃。

I want to put a progressbar spinning object in this activity until Fragment A is complete, and then reveal the layout with Fragment A and Fragment B side by side. 我想在此活动中放置一个进度条旋转对象,直到Fragment A完成,然后与Fragment A和Fragment B并排显示布局。

But I am unsure how to expose the completion of Fragment A's onResume to the activity. 但是我不确定如何向活动公开片段A的onResume的完成。

In Fragment AI do have a fragmentlistener set up 在Fragment AI中确实设置了fragmentlistener

public void onAttach(final Activity activity) {
    super.onAttach(activity);
    try {
        this.mListener = (TopicListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.getClass().getName()
                + " must implement TopicListener");
    }
}

But now what, thanks. 但是现在,谢谢。

作为Android开发者建议在这里 ,我建议你不要夫妇的片段,并通过你的活动类使用回调。

Use your callback to send you to the activity. 使用您的回调将您发送到活动。

Example of using callbacks with a map fragment 将回调与地图片段配合使用的示例

private MapListeners mLocation;

public interface MapListeners{
    public void onMarkerClick(Marker m);
    public void onLocationChanged(Location location);
}

@Override
public void onAttach(Activity activity){
    super.onAttach(activity);
    try{
        mLocation = (MapListeners)activity;
    }catch(ClassCastException e){
        throw new ClassCastException(activity.toString() + " must implement OnMarkerClick and OnLocationChanged");
    }
}

public boolean onMarkerClick(Marker marker) {
//marker is clicked so send a call to the activity like this
    mLocation.onMarkerClick(marker);
    return true;
}

In the activity make sure you implement the interface, in this case it would be MapListeners 在活动中,请确保实现接口,在这种情况下,接口应为MapListeners

then when a marker was clicked the onMarkerClick method you created gets called 然后单击标记时,您创建的onMarkerClick方法将被调用

public void onMarkerClick(Marker m) {

    //do something
}

do this: 做这个:

public class MyFragmentOne extends Fragment{ 
 @Override 
 onResume()
 {
   //Do the complex task
     ((MyActivity)getActivity()).fragmentTaskCompleted();
  }
 }


 public class MyActivity extends Activity
 {
  public void fragmentTaskCompleted()
  {
    //Show second fragment
   }
  }

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

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