更好的方法片段之间的通信是使用一个回调接口,
- 您创建一个包含搜索栏文本
- 那么您实现上的活动该接口的片段接口
- 在具有搜索文本,也创造了接口的片段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它的工作! –