android - 如何将消息从fragment发送到activity并在activity中接收和使用?

标签 android android-fragments android-activity message

请不要删除我在谷歌搜索时感到困惑的问题。 我用过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/

相关文章:

android - ContentProvider、Loader 和 ProgressBar

切换 fragment 后,Android TabLayout 不再显示内容

Android:进度对话框

java - 返回当前的 android 布局或屏幕宽度以进行调试

android - 如何动态设置orderInCategory?

java - 代码适用于 Activity 但不适用于 Fragment

android - Bluetooth Intent 的 Bluetooth startActivity 方法

Android Activity堆栈和返回函数问题

android - 在没有自定义数组适配器的情况下提供 ListView 项目标签

android - OpenGL ES 线程上的垃圾收集