创建一个接口以与另一个片段进行通信 [英] Create an interface to communicate with another fragment

查看:81
本文介绍了创建一个接口以与另一个片段进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个接口,以便当我在FragmentA上按下TextView时可以在FragmentB上设置文本.某事不起作用,我无法解决.

I created an interface so I can set text on a FragmentB when I press a TextView on FragmentA. Something is not working and I can't figure this out.

我创建了一个名为Communicator的界面:

I've created an interface called Communicator:

public interface Communicator {
void respond(String data);

}

在FragmentA上,我在名为Communcator的接口上设置了一个引用,并在TextView上设置了一个OnClickListener:

On FragmentA I've set a reference on the interface called Communcator and an OnClickListener on the TextView:

Communicator comm;

homeTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            comm.respond("Trying to set text on FragmentB from here");
        }
    });

FragmentB,设置我的方法来更改文本:

FragmentB, set my method to change text:

 public void setText(final String data) {
    startTripTxt.setText(data);
}

最后在MainActivity中,我实现了接口..我认为这是我做错事情的地方:

Finally in MainActivity I've implemented the interface .. I think here is where I'm doing something wrong:

 @Override
public void respond(String data) {

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container_main, new FragmentB(), "fragment2").addToBackStack(null).commit();

    FragmentB fragmentB= (FragmentB) getSupportFragmentManager().findFragmentByTag("fragment2");
    if (fragmentB != null) {
        fragmentB.setText(data);
    }


}

加载了片段2,但文本为空.

Fragment 2 loads, but the text is empty.

推荐答案

片段2已加载,但文本为空.

Fragment 2 loads, but the text is empty.

您可以实现Communicator,但是调用FragmentB并传递数据的方式却不正确.这就是为什么您无法从FragmentB获取文本的原因.将数据发送到FragmentB的正确方法应该是这样的:

You implement Communicator is ok but the way you call FragmentB and passing data is not ok. That 's is the reason why you cannot get text from FragmentB. the right way to send data to FragmentB should be like this:

public static FragmentB createInstance(String data) {
        FragmentB fragment = new FragmentB();
        Bundle bundle = new Bundle();
        bundle.putString("data", data);
        fragment.setArguments(bundle);
        return fragment;
    }

您可以通过以下方式从FragmentB获取数据:

And you can get data from FragmentB by:

Bundle bundle = getArguments();
        if (bundle != null) {
             String data = bundle.getString("data");
        }

这篇关于创建一个接口以与另一个片段进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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