Search code examples
javaandroidandroid-alertdialogandroid-tablayoutandroid-viewpager2

Custom TabLayout in AlertDialog using ViewPager2


I am relatively new to writing apps and I am currently working at my second project. I have an activity called AddNetwork, which contains a button that should open an AlertDialog. In the AlertDialog I want to have a TabLayout with two tabs, that each show different content. I have been trying to achieve this for about 8 hours and I have found a few tutorials that partially cover my problem, but nothing that is really on point. I think I could solve my problem using ViewPager2, but I haven't managed to get it working yet. As of now my code works as follows:

AddNetwork.java creates an instance of AlertDialogSelectWifi.java, which extends DialogFragment and inflates the alertdialog_select_wifi.XML layout file that contains a TabLayoutand a ViewPager2. Also in the DialogFragment, I am trying to set an adapter to the viewPager, namely ViewPagerAdapter.java, which extends FragmentStateAdapter. From there I would want to attach the two fragments AlertDialogRecentFragment.java (with fragment_alert_dialog_recent.xml) and AlertDialogTypeFragment.java (with fragment_alert_dialog_type.xml). Note that the latter is not yet included in the code, so as of now I would only add one fragment to the tabs (I guess). So at the moment, my code is a somewhat chaotic mixture of all the tutorials I found and followed. It does not cause any errors and I am able to open the Alertdialog, however, the fragment_alert_dialog_recent.xml and the tabs are not visible. I really don't know what else I could try or change in my code. Overall I am not sure whether it is correct to set the ViewPagerAdapter in the AlertDialogSelectWifi.java file or not. What am I missing or doing wrong? Any help is grealty appreciated!

Here is my code:

AddNetwork.java

public class AddNetwork extends AppCompatActivity {

    Context context = this;

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


        //BUTTON
        final MaterialButton buttonSelectWifi;
        buttonSelectWifi = (MaterialButton) findViewById(R.id.button2);
        buttonSelectWifi.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                //CREATE ALERT DIALOG
                FragmentManager fm = getSupportFragmentManager();
                DialogFragment dialog = AlertDialogSelectWifi.newInstance(context);
                dialog.show(fm, "dialog");

            }
        });
    }
}

AlertDialogSelectWifi.java

public class AlertDialogSelectWifi extends DialogFragment {

    static Context mContext;

    public static AlertDialogSelectWifi newInstance(Context context) {
        mContext = context;
        return new AlertDialogSelectWifi();
    }


    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogTheme);

        LayoutInflater inflater = requireActivity().getLayoutInflater(); //getActivity().getLayoutInflater();
        View alertLayout = inflater.inflate(R.layout.alertdialog_select_wifi, null);

        builder.setTitle("Add Saved Network")
                .setView(alertLayout)
                .setCancelable(true)
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        return builder.create();
    }

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

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


        ViewPager2 viewPager = view.findViewById(R.id.viewpager);
        TabLayout tabLayout = view.findViewById(R.id.tablayout);
        ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity(), mContext, viewPager);

        viewPager.setAdapter(adapter);

        new TabLayoutMediator(tabLayout, viewPager,
                new TabLayoutMediator.TabConfigurationStrategy() {
                    @Override
                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                        tab.setText("Tab " + (position + 1));
                    }
                }).attach();
    }
}

ViewPageAdapter.java

public class ViewPagerAdapter extends FragmentStateAdapter {

    private LayoutInflater mInflater;
    private ViewPager2 viewPager;

    public  ViewPagerAdapter(FragmentActivity fragmentActivity, Context context, ViewPager2 viewPager) {
        super(fragmentActivity);
        this.mInflater = LayoutInflater.from(context);
        this.viewPager = viewPager;
    }

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

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

Solution

  • if i understood your problem correctly change your adapter like this:

    public class ViewPagerAdapter extends FragmentStateAdapter {
    
    public  ViewPagerAdapter(FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }
    
    @NonNull
    @Override
    public Fragment createFragment(int position) {
        if(position == 0)
        return new AlertDialogRecentFragment();
        else
        return new AlertDialogTypeFragment();
    }
    
      @Override
      public int getItemCount() {
        return 2;
      }
    }