Create an interface to communicate with another fragment

做~自己de王妃 提交于 2019-12-13 06:40:09

问题


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.

I've created an interface called Communicator:

public interface Communicator {
void respond(String data);

}

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, set my method to change text:

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

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


}

Fragment 2 loads, but the text is empty.


回答1:


Fragment 2 loads, but the text is empty.

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

And you can get data from FragmentB by:

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



回答2:


It looks like after you declare fragmentB, you're meaning to set the text on that fragment. You are Instead calling trainFinderFragment.setText(). Is that your issue?

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


来源:https://stackoverflow.com/questions/42195888/create-an-interface-to-communicate-with-another-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!