如何将消息从片段发送到活动并在活动中接收和使用?

use*_*062 2 android message android-fragments android-activity

请不要忽略我在谷歌搜索时感到困惑的问题。当用户按下活动上的设置按钮时,我在代码中使用了带有可滑动查看视图的Android选项卡布局

现在,我需要从TopRatedFragment.java发送消息,该消息从片段扩展到调用“带有可滑动查看的Android选项卡布局”的mainActivity的活动。

Ame*_*een 5

您可以通过实施回叫来实现

首先创建一个界面

public interface CommunicationInterface {

public void onSuccess();

public void onFailed();

}
Run Code Online (Sandbox Code Playgroud)

然后在您的活动中实现界面

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
}

}
Run Code Online (Sandbox Code Playgroud)

现在在片段中

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;
}
}
Run Code Online (Sandbox Code Playgroud)