我使用單個活動并將多個片段嵌入其中。現在我想知道在單個活動類中,當前正在顯示哪個片段。我怎樣才能做到這一點?我從這里查看了解決方案如何知道片段是否可見?
MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
//DO STUFF
}
else {
//Whatever
}
但我不知道引數對你來說是什么"testID"
。此外,我嘗試從獲取當前片段物件中實作解決方案
Fragment currentFragment = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
但在這里我收到錯誤訊息:“無法決議符號'fragment_container'”
有誰知道如何獲取使用單個活動和多個片段方法時顯示的當前片段的名稱?
uj5u.com熱心網友回復:
我知道我的這里已經有 2 個答案,但還有 1 個解決方案,所以我在這里寫。這是代碼:
NavController navController = Navigation.findNavController(this, R.id.fragment);
int id=navController.getCurrentDestination().getId();
if(id==R.id.startGameFragment ){ // change the fragment id
selectedPosition(0);
}else if(id==R.id.gameFragment ){ // change the fragment id
selectedPosition(1);
}else if(id==R.id.endGameFragment ){ // change the fragment id
selectedPosition(2);
}
uj5u.com熱心網友回復:
您的第一種方法:
如果您想按標簽查找片段,您需要先設定標簽。您在進行交易時執行此操作,例如:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, SheetEditorScreen.class, args, "testID" //Here you set the tag
)
然后您將能夠像以前一樣按標簽獲取片段:
getSupportFragmentManager().findFragmentByTag("testID");
你的第二種方法:
如果您想通過 id 獲取片段,您需要傳遞您在活動的布局 xml 檔案中宣告的容器的視圖 id(在 中設定setContentView(R.id.main_activity)
):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.fragment.app.FragmentContainerView
android:id="@ id/fragment_container" <--- here is the id
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
然后你可以找到可見的片段:
getSupportFragmentManager().findFragmentById(R.id.fragment_container);
uj5u.com熱心網友回復:
你可以這樣做:
Fragment
在您的活動中創建一個欄位。像這樣:
private Fragment mCurrentlyDisplayingFragment;
- 每當更改片段時,只需將該片段物件傳遞給它。像這樣:
MyFragment fragment = new MyFragment();
// show it in the frame layout
mCurrentlyDisplayingFragment = fragment;
現在,每當您檢查時,只需檢查此欄位。完畢
快樂編碼??
uj5u.com熱心網友回復:
現在,因為我對您的問題更加清楚,我正在添加另一個解決方案。這與FrameLayout
碎片交易一起作業。但是,這也適用NavController
。試試這個代碼:
public Fragment getCurrentlyVisibleFragment(){
Fragment navHostFragment = getSupportFragmentManager().findFragmentById(R.id.navHostFragment);
return navHostFragment == null ? null : navHostFragment.getChildFragmentManager().getFragments().get(0);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460276.html