首頁  >  文章  >  如何從另一個fragment取得recycleView的fragment onViewCreated中的資料?

如何從另一個fragment取得recycleView的fragment onViewCreated中的資料?

王林
王林轉載
2024-02-11 17:51:09475瀏覽

在Android開發中,Fragment是一個重要的元件,用於建立靈活的使用者介面。在使用Fragment時,有時候我們需要從一個Fragment中取得另一個Fragment中的資料。那麼在fragment的onViewCreated方法中,我們可以透過findViewById方法來取得其他Fragment中的RecyclerView中的資料。首先,我們需要確保在獲取資料之前,RecyclerView已經被初始化並填充了資料。然後,我們可以透過FragmentManager的findFragmentById方法來取得目標Fragment的實例,再透過實例的findViewById方法來取得RecyclerView的實例。最後,我們可以透過RecyclerView的適配器來取得資料。這樣,我們就可以在目前的Fragment中取得到另一個Fragment中RecyclerView的資料了。這是一個簡單而有效的方法,可以幫助我們在Android開發中更好地處理資料的傳遞和共享。

問題內容

我有片段 workoutfragment 和 bundle,用於將資料傳輸到片段 delitefragment:

fragmentmanager fragmentmanager = getfragmentmanager();
 fragmenttransaction fragmenttransaction = fragmentmanager.begintransaction();
 fragmenttransaction.replace(r.id.fragment_container, new delitefragment());
 fragmenttransaction.commit();

在 delitefragment 中,我有一個 onviewcreated 方法,其中回收器視圖資料呼叫被鎖定。

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);


    //******************************** getting data from DeliteFragment
    getParentFragmentManager().setFragmentResultListener("text from WOF to AFJ", this, new FragmentResultListener() {
        @Override
        public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle textBundle) {

            Integer number_workout_train_position = textBundle.getInt("text from WOF to AFJ");
            String nameDayTrain  = new   CardSourceImplDayTrain(getActivity()).getCardData(number_workout_train_position).getTitle().toString();

        }
    });

String nameDayTrainRW = nameDayTrain;

         recyclerView = view.findViewById(R.id.train_delite_recycleView);
        cardSource = new CardSourceImplDelite(getActivity().getApplicationContext(),nameDayTrainRW,nameDayTrainRW);
        adapter = new itemAdapterDelite(cardSource);
   }

如何在 onviewcreated 中取得資料 namedaytrain? (所以它將轉到recyclerview適配器)

解決方法

使用 AndroidX 視圖模型庫與您的 Activity 和片段進行通訊。這非常簡單✍️

這裡: AndroidX Jetpack ViewModel

以上是如何從另一個fragment取得recycleView的fragment onViewCreated中的資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除