请不要删除我在谷歌搜索时感到困惑的问题。 我用过Android Tab Layout with Swipeable Views在我的代码中,当用户按下 Activity 上的设置按钮时。
现在我需要从 TopRatedFragment.java 发送消息,该消息从 fragment 扩展到调用“具有可滑动 View 的 Android 选项卡布局”的 mainActivity 的 Activity 。
最佳答案
您可以通过实现回调来做到这一点
首先创建一个接口(interface)
public interface CommunicationInterface {
public void onSuccess();
public void onFailed();
}
然后在您的 Activity 中实现接口(interface)
public class YourActivity extends ActionBarActivity implements CommunicationInterface {
//default functions
@Override
public void onSuccess() {
//stuff you want to do in the acivity
}
@Override
public void onFailed() {
//stuff you want to do in the acivity
}
}
现在在 fragment 中
public class yourfragment extends Fragment {
CommunicationInterface callback;
//stuffs that usually come in yor fragment and like OncreateView etc
@Override
public void onActivityCreated(@Nullable Bundle outState) {
super.onActivityCreated(outState);
//after all the stuff you want to do in your fragment then implement //call back function to communicate with the activity
callback= (CommunicationInterface) getActivity();
callback.onSuccess();//according to your purpose use where ever you like
callback.onFailed();//according to your purpose use where ever you like
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback= (CommunicationInterface) activity;
}
}
关于android - 如何将消息从fragment发送到activity并在activity中接收和使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23311629/