2017-06-14 81 views
0

我有一个具有ViewPager的片段。 ViewPager内部的每个片段显示一些基于主片段中的SearchBar的数据。主片段还有一个名为getKeyword()的公共方法(返回SearchBar的字符串)。但我不知道如何获得ViewPager片段中主要片段的引用。ViewPager中片段之间的通信

我尝试使用onAttach()方法获取参考,但它返回mainActivity的引用。

我也尝试使用getChildFragmentManager()来获取主要片段,但我不知道什么是主要片段的ID(主要片段实际上是另一个ViewPager的片段)。

+0

使用事件来这里通知每个用户 – Eenvincible

+1

你试过打电话给getParentFragment()?什么是“主要碎片”? – Buckstabue

+0

@Buckstabue它的工作! –

回答

2

更好的方法片段之间的通信是使用一个回调接口,

  1. 您创建一个包含搜索栏文本
  2. 那么您实现上的活动该接口的片段接口
  3. 在具有搜索文本,也创造了接口的片段onAttach方法创建界面回调的一个实例,并填写铸造活动到回调的情况下

public class MainFragment extends Fragment {

//all your other stuff 
    private MyFragment.Callback myCallback; 

    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     if(activity instanceOf MyFragment.Callback) { 
      myCallback = (MyFragment.Callback) activity; 
     } else { 
      /*here you manage the case when the activity does not have the interface callback implemented*/ 
      //Generally with this 
      throws new ClassCastException(
       activity.class.getSimpleName() + 
       " should implement " + 
       MyFragment.class.getSimpleName() 
       ); 
     } 
    } 

    private void thisMethodIsUsedWhenTheSearchIsExecuted(String searchText) { 
     //here you get the string of the search however you need 
     myCallback.callWhenSearch(searchText); 
    } 

    public interface Callback { 
     void callWhenSearch(String searchText); 
    } 
} 

下面是管理的片段

public class MyActivity extends AppCompatActivity implements MyFragment.Callback { 
// anything you need for the main activity 
    public void callWhenSearch(String searchText) { 
    //searchText will contain the text of the search executed on MyFragment 
    //and here you can execute a method that calls the fragment where you need to see the result of your search for example 

     instanceOfSecondFragment.visualizeResultsOf(searchText) 

    } 
} 

你可以在这里的一些官方文件的活动代码:

Communicating with Other Fragments

如果您需要更多请帮助,让我知道。

+0

好的探索 –

+0

我尝试过这个解决方案,但问题是当我尝试施放'Activity'时,我得到的是MainActivity而不是Fragment。 –