片段之间如何通信? [英] How to communicate between fragments?

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

问题描述

我正在开发一个Android应用程序.我有一个要求,例如片段1中有一个按钮,当用户单击该按钮结果应显示在片段2中时.在加载活动时,两个片段都被附加了.这是我的尝试:

I am developing an Android application. I have a requirement like there is a button in fragment 1, when a user clicks that button result should be displayed in fragment 2. While loading the activity both fragments is attached. Here is my try:

在主要活动中:

    public void dsp(String str) {
    secondfragment f2=new secondfragment();
    Bundle bundle = new Bundle();
    bundle.putString("edttext", "From Activity");

    f2.setArguments(bundle);
    }

在第一个片段中:

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.fragone, container,false);
    Button btn = (Button) v.findViewById(R.id.button1); 
    btn.setOnClickListener(new OnClickListener() {           
          @Override
          public void onClick(View v) 
          {
              m.dsp("clicked");
          }    
        });
    return v;
}

第二个片段:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v=inflater.inflate(R.layout.fragtwo, container,false);
    tv= (TextView) v.findViewById(R.id.textView1);

    tv.setText(this.getArguments().getString("name"));

    return v;
}

推荐答案

当从Fragment到Fragment进行通信时,您可以使用接口将数据传递给Activity,从而依次更新您要更改的片段.

When communicating from Fragment to Fragment you use an interface to pass data to the Activity which in turn updates the fragment you want to change.

例如:

在片段1中:

public class FragmentOne extends Fragment{

  public Callback mCallback;

  public interface Callback{
       void onUpdateFragmentTwo(String message);
  }


   @Override
   public void onAttach(Activity activity){
     super.onAttach(activity);
     mCallback = (Callback) activity;
   }

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.fragone, container,false);
        Button btn = (Button) v.findViewById(R.id.button1); 
        btn.setOnClickListener(new OnClickListener() {           
            @Override
           public void onClick(View v) {
               mCallback.onUpdateFragmentTwo("clicked");
            }     
        });
     return v;
  }
}

然后在主Activity中实现该接口:

then in main Activity implement the interface:

public class MainActivity extends AppCompatActivity implements Callback{

  FragmentTwo fragmentTwo;
  @Override
  public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);

     // ... Load views or perform logic

     // ... Load Fragment Two into your container
     if(savedInstanceState == null){
         fragmentTwo = FragmentTwo.newInstance(new Bundle()); // use real bundle here
         getSupportFragmentManager()
             .beginTransaction()
             .add(R.id.fragment_holder, fragmentTwo, "Frag2").commit();
     }
  }


  // Interface method
  @Override
  public void onUpdateFragmentTwo(String message){
     // Call activity method with the argument
     if(fragmentTwo != null){
          fragmentTwo.updateFragmentTwo(message);
     }
  }

}

更新

在您的第二个片段中,我通常使用静态的newInstance(Bundle args)方法进行初始化,然后将使用公共方法从Activity到Fragment进行通信,例如:

In your second fragment I typically use a static newInstance(Bundle args) method to initialize and then would use a public method to communicate from the Activity to the Fragment for example:

 public class FragmentTwo extends Fragment{

      public static FragmentTwo newInstance(Bundle args){
          FragmentTwo fragment = new FragmentTwo();
          fragment.setArguments(args);
          return fragment;
      }

      //... Class overrides here onCreateView etc..

      // declare this method 
      public void updateFragmentTwo(String updateText){
         // .. do something with update text
      }

 }

就这样,祝您编程愉快!

Thats it, happy coding!

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

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