[英]How to change fragment from another fragment an apply it on the main_content layout?
我正在努力從另一個片段中更改一個片段。 在我的main_activity中,我有一個具有bottomnavigationview的布局文件和頁面內容的框架布局。 在NavigationView上從片段到片段的更改工作正常,但是如果我從片段訪問新的“子片段”,則新片段是透明的。
有什么建議么? 下面的代碼來自我的片段和我的mainactivity。
MainActivity parentActivity = (MainActivity) getActivity();
parentActivity.switchContent(new VisArrangementInfo(), data, true);
MainActivity中的switchContent:
public void switchContent(final Fragment fragment, Bundle data, final Boolean addToBackStackOption){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
}
id content_frame是MainActivity的布局文件的ID。 bottomnavigationview和framelayout在此文件中。 框架布局的ID為“ main_frame”。
在我理解之后,我想更改“ main_frame”而不是“ content_fram”,因為這里應該是主要內容。 當我這樣做時,我找不到片段的布局,我嘗試完全打開。 是因為我要替換框架布局而不是整個布局嗎?
在Fragment A
定義一個接口。
public interface FragmentEventListener {
void onFragmentChangeEvent(Fragment newFragment);
}
private FragmentEventListener listener;
public void setEventListener(FragmentEventListener listener) {
this.listener = listener;
}
在片段中,當您想更改片段時,請調用方法。
if (listener != null) {
listener.onFragmentChangeEvent(FragmentB);
}
在您的主要活動中,實現FragmentEventListener
,以便您可以從MainActivity切換到Fragment B
。
public class MainActivity implements FragmentA.FragmentEventListener {
...
...
fragmentB.setEventListener(this); // here identify the listener.
....
@Override
public void onFragmentChangeEvent(Fragment newFragment) {
switchContent // Switch to Fragment B here
}
第一次使用add
而不是replace
:
public void switchContent(final Fragment fragment, Bundle data, final Boolean addToBackStackOption){
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content_frame, fragment)
.addToBackStack(null)
.commit();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.