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

时间:2014-04-26 13:32:29

标签: android android-fragments android-activity message

请不要在谷歌搜索时弄糊涂我的问题。 我在代码中使用了Android Tab Layout with Swipeable Views,用户在活动时按下设置按钮。

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

4 个答案:

答案 0 :(得分:4)

您可以通过实施回拨

来实现此目的

首先创建一个界面

public interface CommunicationInterface {

public void onSuccess();

public void onFailed();

}

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

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
}

}

现在在片段中

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;
}
}

答案 1 :(得分:3)

仔细看看这个参考: Creating event callbacks to the activity

答案 2 :(得分:0)

android文档推荐使用这种模式让父活动实现片段的接口(基本上调用方法)

class MyFragment extends Fragment {
    interface Listener {
        public void onSomeEvent();
    }

    private void somethingHappeninInTheFragment() {
        // let the activity know
        ((Listener) getActivity()).onSomeEVent();
    }
}

class MyActivity extends Activity implements MyFragment.Listener {
    // etc
    @Override
    public void onSomeEvent() {
        // handle the message from the fragment
    }
}

在这里用更具体的例子进行解释:http://developer.android.com/guide/components/fragments.html#EventCallbacks

答案 3 :(得分:0)

以下是解决方案:

第1步:从您的片段开始。

Intent i = new Intent(getActivity(), YourActivity.class);
        i.putExtra("key", "Your value1");
        i.putExtra("key2", "Your value2");
        i.putExtra("key3", "Your value3");
        getActivity().startActivity(i);

第2步:在您想要结果的活动中

Intent getResults = getIntent();
        String firstValue = getResults.getStringExtra("key1");
        String secondValue = getResults.getStringExtra("key2");
        String thirdValue = getResults.getStringExtra("key3");

使用您需要的那些值。

希望这会有所帮助.. :)