简体   繁体   中英

How to pass data from a fragment to an adapter

Let me quickly explain my code structure, I have a dynamic tab layout with a dynamic fragment. The tabs are fetched from a json response, and the each tab has a dynamic fragment with a recycler view populated from a json response as well.

I'm in trying to pass the id of the selected tab to the recycler view's adapter

1. TransactionsFragment(Where the tab layout is created)

 for(int i=0;i<array.length();i++) {

                                //getting wallet object from json array
                                JSONObject userWallets=array.getJSONObject(i);

                                tab.addTab(tab.newTab().setText(userWallets.getString("wallet_name")));
                                walletID.add(userWallets.getInt("id"));
                            }

                            TransactionsPagerAdapter adapter = new TransactionsPagerAdapter
                                    (getChildFragmentManager(), tab.getTabCount(), walletID); //the data i need to pass is the walletID
                            viewPager.setAdapter(adapter);
                            viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab));
                            adapter.notifyDataSetChanged();

2. TransactionsPagerAdapter(adapter controlling the tabs)

public class TransactionsPagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;
    ArrayList<Integer> walletID;

    public TransactionsPagerAdapter(FragmentManager fm, int NumOfTabs, ArrayList<Integer> walletID) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        this.mNumOfTabs = NumOfTabs;
        this.walletID = walletID;
    }

    @Override
     public Fragment getItem(int position) {
    DynamicFragment d = new DynamicFragment();
    Bundle args = new Bundle();
    args.putInt("your_key", walletID.get(position));
    d.setArguments(args);
    return d.newInstance(walletID.get(position));

}

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
    }

3. DynamicFragment(Where recycler view in each tab is populated)

for(int i=0;i<array.length();i++) {

                                //getting wallet object from json array
                                JSONObject userTransactions=array.getJSONObject(i);

                                //adding the wallet to wallet list
                                userTransactionList.add(new Transaction(
                                        userTransactions.getInt("id"),
                                        userTransactions.getInt("wallet_id"),
                                        userTransactions.getDouble("fee"),
                                        userTransactions.getDouble("amount"),
                                        userTransactions.getDouble("from"),
                                        userTransactions.getDouble("to"),
                                        userTransactions.getString("destination_address"),
                                        userTransactions.getString("type"),
                                        userTransactions.getString("created_at")
                                ));
                            }

                            //creating adapter object and setting it to recyclerview
                            TransactionsAdapter adapter = new TransactionsAdapter(getActivity(),childFragmentManager, userTransactionList);
                            mRecyclerView.setAdapter(adapter);
                            swipeRefreshLayout.setRefreshing(false);
                            // stop animating Shimmer and hide the layout
                            mShimmerViewContainer.stopShimmerAnimation();
                            mShimmerViewContainer.setVisibility(View.GONE);
//                            progressDialog.dismiss();
                            adapter.notifyDataSetChanged();

4. TransactionsAdapter(adapter controlling the recycler views)

public class TransactionsAdapter extends RecyclerView.Adapter<TransactionsAdapter.DataObjectHolder> {

    private static String TAG = TransactionsAdapter.class.getSimpleName();

    private Context mCtx;
    private FragmentManager fragmentManager;

    private ArrayList<Transaction> userTransactionList;
    private static MyClickListener myClickListener;

    public TransactionsAdapter(Context mCtx, FragmentManager fragmentManager, ArrayList<Transaction> userTransactionList) {
        this.mCtx = mCtx;
        this.fragmentManager = fragmentManager;
        this.userTransactionList = userTransactionList;
    }

    public static class DataObjectHolder extends RecyclerView.ViewHolder {
        TextView transactionamount, transactionstatus, transactionid;
        ImageView transactionicon, pendingicon;

        public DataObjectHolder(View itemView) {
            super(itemView);
            transactionamount = (TextView) itemView.findViewById(R.id.amount);
            transactionstatus = (TextView) itemView.findViewById(R.id.status);
            transactionicon = (ImageView) itemView.findViewById(R.id.tx_icon);
            pendingicon = (ImageView) itemView.findViewById(R.id.img_status);
            transactionid = (TextView) itemView.findViewById(R.id.wallet_id);
        }

    }

        @Override
        public TransactionsAdapter.DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mCtx).inflate(R.layout.transaction_item, parent, false);
            final TransactionsAdapter.DataObjectHolder dataObjectHolder = new TransactionsAdapter.DataObjectHolder(view);
            return dataObjectHolder;
        }


        @Override
        public void onBindViewHolder(TransactionsAdapter.DataObjectHolder holder, final int position) {

            DecimalFormat formatter = new DecimalFormat("###,###,###,###,###.##");
            formatter.setDecimalSeparatorAlwaysShown(true);
            formatter.setMinimumFractionDigits(2);
            Double doubleBalance = userTransactionList.get(position).getTransactionAmount();
            String numberFormatBalance = formatter.format(doubleBalance);
            holder.transactionstatus.setText(userTransactionList.get(position).getTransactionType());
            holder.transactionamount.setText(String.valueOf("₦ " + numberFormatBalance));
            if ((userTransactionList.get(position).getTransactionType()).equals("send")) {
                holder.transactionicon.setImageResource(R.drawable.ic_communication_call_made);
            } else  {
                holder.transactionicon.setImageResource(R.drawable.ic_communication_call_received);
            }

        }


        @Override
        public int getItemCount() {
            return userTransactionList.size();
        }

        public interface MyClickListener {
            public void onItemClick(int position, View v);
        }
    }

I need to get the walletID from 1(TransactionsFragment) to 4(TransactionsAdapter), is this possible, if so how, I know for a fact this cannot be done with bundle since we aren't creating an intent

  1. Make sure you put walletId to Arguments of DynamicFragment by
DynamicFragment.newInstance(walletID.get(position))
  1. Modify constructor of TransactionsAdapter follow this
private Integer walletId;

public TransactionsAdapter(Context mCtx, FragmentManager fragmentManager, ArrayList<Transaction> userTransactionList, Integer walletId) {
        this.mCtx = mCtx;
        this.fragmentManager = fragmentManager;
        this.userTransactionList = userTransactionList;
        this.walletId = walletId;
    }


  1. In DynamicFragment when you init TransactionsAdapter get walletId from arguments of fragment
Integer walletId = getArguments().getInt("your_key") // your key when you newInstance and put to Bundle
TransactionsAdapter adapter = new TransactionsAdapter(getActivity(),childFragmentManager, userTransactionList);

Finally, your adapter has information of walletId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM