更好的方法片段之間的通信是使用一個回調接口,
- 您創建一個包含搜索欄文本
- 那麼您實現上的活動該接口的片段接口
- 在具有搜索文本,也創造了接口的片段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
如果您需要更多請幫助,讓我知道。
使用事件來這裏通知每個用戶 – Eenvincible
你試過打電話給getParentFragment()?什麼是「主要碎片」? – Buckstabue
@Buckstabue它的工作! –