Answer the question
In order to leave comments, you need to log in
How to send data from Activity to Fragment with ViewPager2 connected?
Hello!
I am trying to send data from MainActivity to one of the fragments created with ViewPager2.
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
ViewPager2 viewPager = findViewById(R.id.viewPager);
MainPagerAdapter pagerAdapter = new MainPagerAdapter(this);
viewPager.setAdapter(pagerAdapter);
}
public class MainPagerAdapter extends FragmentStateAdapter
{
public MainPagerAdapter(@NonNull FragmentActivity fragmentActivity)
{
super(fragmentActivity);
}
@NonNull
@Override
public Fragment createFragment(int position)
{
switch (position)
{
case 0:
return new Fragment1();
case 1:
return new Fragment2();
default:
return new Fragment3();
}
}
@Override
public int getItemCount()
{
return 3;
}
}
Fragment1 fragment1 = new Fragment1();
Bundle bundle = new Bundle();
bundle.putInt("1", 1);
fragment1.setArguments(bundle);
Bundle bundle = this.getArguments();
if (bundle != null)
{
int i = bundle.getInt("1", 0);
Log.d(Constants.LOG_TAG, "" + i);
}
Answer the question
In order to leave comments, you need to log in
At the time the activity is created, the fragment does not yet exist. You, judging by the code, created it, filled it with data, and then just threw it away. The pager has created a new fragment for itself.
One of the ways here is to make a certain repository with data, where the activity will add them, and the fragment will take it from there when it needs the data. Store the repository in an activity or in a DI graph.
Another easier way is to use the adapter as intended. He, as planned, adapts (turns) the data into fragments. Pass your data from the activity to the adapter, and when creating a fragment in the adapter, fill it with this data.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question