Search code examples
androiddialogandroid-viewpagerandroid-tablayoutcustomdialog

How can I change the tab with a click response from a custom dialogue box in a tab layout


The custom dialogue box has been called from the fragment itself and I want to move to next tab when the dialogue box return positive and stay on the same tab when dialogue box return negative.

Dialogbox code in fragment

  Dialog_days_selection dds = new Dialog_days_selection(getActivity());
                dds.show();
                dds.setDialogResult(new Dialog_days_selection.OnMyDialogResult() {
                    @Override
                    public void finish(int result) {
                        currentItem = result;
                        if (currentItem==2){

                            ((Subscription) getActivity()).getTabLayout().getTabAt(2).select();

                        }
                    }
                });

Dialog Box code for handling click events

 @Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_ok_dialog_address:
            mDialogResult.finish(count = 2);
            dismiss();
            break;

        case R.id.btn_cancel_dialog_address:
            mDialogResult.finish(count = 1);
            dismiss();
            break;
        default:
            break;
    }
    dismiss();
}


public void setDialogResult(OnMyDialogResult dialogResult) {
    mDialogResult = dialogResult;
}

public interface OnMyDialogResult {
    void finish(int result);
}

Getter method in Activiity

public TabLayout getTabLayout() {
    return tabLayout;
}

Solution

  • First create a getter method to obtain tablayout from your Activity

    TabLayout getTabLayout() {
        return tabLayout;
    }
    

    You might have made logic in your Fragment to show the AlertDialog. Use the following piece of code in your dialog action to change the tab.

    ((YourActivity) getActivity()).getTabLayout().getTabAt(INDEX_OF_THE_NEW_TAB).select();