View pager2 in Fragment of BottomNavigation

382 Views Asked by At

I have 2 Fragment,Frag1 and Frag2 in Bottom navigation and in Frag1 I have implemented retrofit through viewmodel(MVVM) and when I try to send query by buttons in viewpager2 to frag1..getactivity is null..also attach detach do not work.

Please suggest some ways.

1

There are 1 best solutions below

0
On

Implement fragments like this in your activity_main.xml layout:

<fragment
            android:id="@+id/frag1"
            android:name="com.example.app.Frag1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout="@layout/frag1" />
<fragment
            android:id="@+id/frag2"
            android:name="com.example.app.Frag2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:layout="@layout/frag2" />

Now in your MainActivity.java file:

FragmentManager manager;
Frag1 frag1;
Frag2 frag2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    manager = getSupportFragmentManager();

    frag1 = (Frag1) manager.findFragmentById(R.id.frag1);
    frag2 = (Frag1) manager.findFragmentById(R.id.frag2);
}

public void sendToFrag1(Object data){
    frag1.reciveDataHere(data);
}

In your fragment Frag1.java:

public void recieveDataHere(Object data){
    //you get data here
}

To send the Data:

((MainActivity) getActivity()).sendToFrag1(data);

or ((MainActivity) getContext()).sendToFrag1(data);