【问题标题】:Communicating between two fragments两个片段之间的通信
【发布时间】:2014-01-25 13:38:02
【问题描述】:

我有两个扩展 Fragment 的类。两者都在同一个 Activity 中。我想在另一个片段类中按下按钮时触发 1 个片段类中的方法。我知道这可以使用接口或意图来完成。任何人都给我一个代码示例来执行此操作。 提前致谢

【问题讨论】:

    标签: java android android-fragments android-activity communication


    【解决方案1】:

    :D

    在本例中,FragmentA 调用通知。

    INotifier

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

    实用程序

    public class Utils {
        public static INotifier notifier;
    }
    

    片段A

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

    片段B

    public FragmentB extends Fragment implements INotifier {
    
       public void onCreateView(...) {
           Utils.notifier = this;   
       }
    
       @Override
       public void notify(Object data) {
           // handle data
       }
    }
    

    【讨论】:

    • 我尝试了大多数方法,但从未成功,但这个解决方案指明了方向。
    【解决方案2】:

    我不知道为什么有些程序员把它弄得这么复杂。正如我在您的问题中所了解的那样,您希望在 fragment1 中有一个按钮,当您单击它时,fragment2 的 textView 会发生变化。

    只需在fragment1 和onClick 方法中调用该按钮的onClick,对fragment2 的textView 调用并执行任何您喜欢的操作。

    textView.setText("Hello");
    

    【讨论】:

      【解决方案3】:

      在 FragmentA 中,您可以调用:

      setTargetFragment(Fragment FragmentA)
      

      在 FragmentB 中调用:

      getTargetFragment();
      

      【讨论】: