简体   繁体   中英

Communicating between two fragments

I have two classes that extend Fragment.Both are in the same Activity.I want to fire a method in 1 fragment class when a button is pressed in another fragment class.I know this can be done using an interface or intents.Any one give me a code sample for doing this. Thanks in advance

:D

In this example, FragmentA call notify.

INotifier

public interface INotifier {
    public void notify(Object data);
}

Utils

public class Utils {
    public static INotifier notifier;
}

FragmentA

public FragmentA extends Fragment {

   public void onCreateView(...) {

   }

   public void inSomeMethod() {
        if (Utils.notifier != null) {
           Utils.notifier.notify(data);
        }
   }
}

FragmentB

public FragmentB extends Fragment implements INotifier {

   public void onCreateView(...) {
       Utils.notifier = this;   
   }

   @Override
   public void notify(Object data) {
       // handle data
   }
}

I don't know why some programmers make it so complicated. As I understand in your question, you want to do like having a button in fragment1 and when you click it, the textView of the fragment2 will change.

Just call the onClick of that button in fragment1 and inside that onClick method, call and do whatever you like to the textView of fragment2.

textView.setText("Hello");

In FragmentA you can call to:

setTargetFragment(Fragment FragmentA)

In FragmentB call to:

getTargetFragment();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM