0

I have 4 fragments but for each fragments it has different different menu options in my app with viewpager2 so the user swipe through these all fragments and when the app starts the menu option for the first fragment showing the wrong which is 4th fragment menu option item that wrongly inflated in 1st fragment whenever I open the app it only occur when I open the app freshly but when I swipe to 2nd fragment and come back to first then it work correctly but at start/opening the app firstly then it shows wrong menu item btw I using setOffScreenPageLimit(4) this problem occurs when I use this method I hope anyone could solve this problem

I guess this is my situation I tried this ->

How to correctly inflate menus for an action bar from viewpager fragments

but it shouldn't work

MR AR
  • 3
  • 1
  • 4
  • Try setting setOffScreenPageLimit to 1, also post the code that you have done so far. So that we could give proper suggestions for your problem. – Bhavnik Sep 05 '22 at 15:36
  • @Bhavnik I tried that and still that didn't work but sorry I can't share the source code cuz it's really a big codebase you got my question right so are there any other ways to fix this? – MR AR Sep 05 '22 at 15:52
  • Use Viewpager2 callback method that will return current position of item and based on that position, inflate the menu item. – Bhavnik Sep 05 '22 at 15:57
  • But it works fine without setOffScreenPageLimit(4) what's the reason for the wrong menu showing when we use this method? I wanted to use this method cuz of the smoothness I wanted do is there's any other solutions? – MR AR Sep 05 '22 at 16:32
  • What I meant is to use OnPageChangeCallback interface of viewpager2. This will override 3 other methods. Among these 3 methods use onPageSelected method, which will return current position of viewpager item. Use that position to inflate options menu for particular viewpager fragment. – Bhavnik Sep 06 '22 at 12:14
  • Oh sounds good I guess wait lemme try it @Bhavnik – MR AR Sep 06 '22 at 13:14
  • @Bhavnik I tried it yesterday but still can't find a way to inflate the menu but it is possible to inflate the menu by onCreateOptionsMenu in Viewpager adaptor callback? if you don't mind please show me some example with code so that I can solve my problem – MR AR Sep 07 '22 at 04:47
  • Okay sure, I will post code for that. – Bhavnik Sep 07 '22 at 06:44
  • @Bhavnik Alright waiting for your code and thank you again – MR AR Sep 08 '22 at 06:58
  • @Bhavnik Sorry for the disturbance you done the code part? If yes kindly share it thanks! – MR AR Sep 11 '22 at 07:16
  • Did it work MR AR? – Bhavnik Sep 20 '22 at 07:17
  • @Bhavnik Sorry for the late reply cuz I was very busy with my work and The menu are inflating but the problem is all the Menu items get inflated in starting of the fragment but in my case, I just wanna show only one menu item for each fragment – MR AR Sep 23 '22 at 05:39
  • Check the below answer again and compare both codes. Hope you will find your answer. – Bhavnik Sep 23 '22 at 06:55
  • @Bhavnik Wait I'll try to Compare it and I update you on what just happened with Screenshots if I can – MR AR Sep 23 '22 at 09:56
  • @Bhavnik Tried it and It's still not working well as I said in a previous comment it behaves the same I think the problem is by the programming language cuz in my case I'm using java as main language – MR AR Sep 23 '22 at 16:48
  • Well, I think language is not a barrier, though I will let you know once I check it in java. – Bhavnik Sep 26 '22 at 09:03
  • @Bhavnik Alright I'm waiting for your Answer thanks – MR AR Sep 27 '22 at 12:39
  • @Bhavnik Hello hru hope you're doing well and I'm still waiting for the code you've found the solution? not yet? lemme know and thanks – MR AR Oct 16 '22 at 07:44
  • Sure, will post the code soon. – Bhavnik Oct 17 '22 at 05:11
  • @Bhavnik Alright thank you waiting for your code! – MR AR Oct 17 '22 at 07:02
  • I have updated my answer from kotlin to Java. Try the below updated code and set logic according to your requirement. – Bhavnik Oct 27 '22 at 06:19
  • Did it work MR AR? – Bhavnik Nov 06 '22 at 09:09
  • I'll update you when it works because i haven't tried it yet because i was in my other projects work and in few days i get back into this project and try your solution anyway again thanks for your solution and I'll update you when I'm done! – MR AR Nov 06 '22 at 09:34
  • @Bhavnik Wow thank you for your solution one of the best solution and my problem solved now! thank you very much Bhavnik hope you have a wonderful day! – MR AR Nov 17 '22 at 07:04
  • But the only problem I'm facing right now is the option menu getting inflate slowly when i scroll through fragments by view pager is there's solution for that too or that's a normal behavior by default by android? – MR AR Nov 17 '22 at 07:14
  • Well, I didn't face that problem at all. I have to look into that matter. – Bhavnik Nov 17 '22 at 12:56
  • Oh alright lemme know when you found the soultion and altho Thanks for your working solution again! – MR AR Nov 17 '22 at 13:44

1 Answers1

0

I am giving you here full source code for your problem. Give it a try and hope it might help you. Create an options menu according to your requirement.

Follow below steps

1 - activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

2 - MainActivity.java

public class ViewPagerActivity extends AppCompatActivity {

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

    initViewPager();
}

private void initViewPager() {
    ViewPager2 viewPager = findViewById(R.id.viewPager);
    ViewpagerAdapter adapter = new ViewpagerAdapter(this);
    viewPager.setAdapter(adapter);

    // Add menu items without overriding methods in the Activity
    addMenuProvider(new MenuProvider() {
        @Override
        public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
            // Add menu items here
            switch (viewPager.getCurrentItem()) {
                case 0:
                    getMenuInflater().inflate(R.menu.menu_one, menu);
                    break;

                case 1:
                    getMenuInflater().inflate(R.menu.menu_two, menu);
                    break;

                case 2:
                    getMenuInflater().inflate(R.menu.menu_three, menu);
                    break;

                case 3:
                    getMenuInflater().inflate(R.menu.menu_four, menu);
                    break;
            }
        }

        @Override
        public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
            return false;
        }
    });
}

}

3 - Your viewpager2 adapter

public class ViewpagerAdapter extends FragmentStateAdapter {

    public ViewpagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return MyFragment.newInstance(position);
    }

    @Override
    public int getItemCount() {
        return 4;
    }
}

4 - Your fragment

public class MyFragment extends Fragment {

    private int fragmentPos = 0;

    public MyFragment(int fragmentPos) {
        this.fragmentPos = fragmentPos;
    }

    public static MyFragment newInstance(int fragmentPos) {
        Bundle args = new Bundle();
        MyFragment fragment = new MyFragment(fragmentPos);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_view, container, false);
    }

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

        setHasOptionsMenu(true);
        AppCompatTextView label = view.findViewById(R.id.tvFragPos);
        label.setText("Current fragment index \n" + fragmentPos);
    }
}

Output

1st Fragment option menu

3rd Fragment option menu

Bhavnik
  • 2,020
  • 14
  • 21