DESCRIPTION:
I have an activity with a view pager and below some image views that are circles which should be colored according to the position of the fragment in which the user is positioned with the view pager.
QUESTION:
How can I send data to the activity when fragment changes are made in the view pager?
EXAMPLE:
When moving from the first fragment (in the view pager) to the second, the first circle would stop being colored so that the second would be colored (representing that the user is positioned in the second fragment).
I attach the JAVA code of the PlaceHolderFragment that changes the fragments
public class PlaceholderFragment_contenedor_app_info extends Fragment {
private model_contenedor_app_info modelo;
//PARA RETORNAR EL FRAGMENT SELECCIONADO
public static Fragment newInstance(int index) {
Fragment fragment = null;
switch(index){
case 1:
fragment = new fragment_sobre_nosotros();
break;
case 2:
fragment = new fragment_ofrecemos_comodidad();
break;
case 3:
fragment = new fragment_en_confianza();
break;
}
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
modelo = ViewModelProviders.of(this).get(model_contenedor_app_info.class);
int index = 1;
if (getArguments() != null) {
index = getArguments().getInt("section_number");
}
modelo.setIndex(index);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View root = inflater.inflate(R.layout.fragment_sobre_nosotros, container, false);
return root;
}
}
If you're using "some images that are circles" you'll probably want to look at the TabLayout component as they are bookmarks to the ViewPager's pages and change automatically when the user does so.
If this is not the case, ViewPager has a listener called addOnPageChangeListener that captures the tab change:
In the onPageSelected(int position) method, you can check the page number and if you want to notify the fragment at that moment, the communication can be done with an interface as you have been told or with a shared ViewModel if you are already using it.