两个片段之间的基本通讯 [英] Basic Communication between two fragments

查看:133
本文介绍了两个片段之间的基本通讯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动 - MainActivity 。在这个活动我有两个片段,这两个我创建声明XML中。

I have one activity - MainActivity. Within this Activity I have two fragments, both of which I created declaratively within the xml.

我想用户传递字符串文字输入片段A 在文本视图片段B 。然而,这已经被证明是非常困难的。有谁知道我会如何实现这一目标?

I am trying to pass the String of text input by the user into Fragment A to the text view in Fragment B. However this is proving to be very difficult. Does anyone know how I might achieve this?

据我所知,一个片段可以得到一个引用它的使用 getActivity()的活动。因此,即时通讯猜我会从那里开始?

I am aware that a fragment can get a reference to it's activity using getActivity(). So im guessing I would start there?

推荐答案

有一个在Android的deverlopers页面: 的http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface

Have a look at the Android deverlopers page: http://developer.android.com/training/basics/fragments/communicating.html#DefineInterface

基本上,你定义在你的片段A的界面,让你的活动实现该接口。现在,你可以在你的片段调用接口的方法,你的活动将接收该事件。现在,在你的活动,你可以叫你的第二个片段与接收到的值更新的TextView

Basically, you define an interface in your Fragment A, and let your Activity implement that Interface. Now you can call the interface method in your Fragment, and your Activity will receive the event. Now in your activity, you can call your second Fragment to update the textview with the received value

// You Activity implements your interface
public class YourActivity implements FragmentA.TextClicked{
    @Override
    public void sendText(String text){
        // Get Fragment B
        FraB frag = (FragB)
            getSupportFragmentManager().findFragmentById(R.id.fragment_b);
        frag.updateText(text);
    }
}


// Fragment A defines an Interface, and calls the method when needed
public class FragA extends Fragment{

    TextClicked mCallback;

    public interface TextClicked{
        public void sendText(String text);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (TextClicked) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement TextClicked");
        }
    }

    public void someMethod(){
        mCallback.sendText("YOUR TEXT");
    }

    @Override
    public void onDetach() {
        mCallback = null; // => avoid leaking, thanks @Deepscorn
        super.onDetach();
    }
}

// Fragment B has a public method to do something with the text
public class FragB extends Fragment{

    public void updateText(String text){
        // Here you have it
    }
}

这篇关于两个片段之间的基本通讯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆