2017-06-14 78 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。 –