Button in the Spinner reset Mainactivity in a Dialogfragment

Asked

Viewed 24 times

0

I have two buttons in Mainactivity, the first opens a custom Dialogfragment with some spinners and the other button resets the spinner of this Dialogfragment.

When I click the reset button it calls this method that is in Dialogfragment:

   public class FilterDialogFragment extends DialogFragment {
    private View view;
    // ...

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

        // start the spinners and adapters here

        return view;
    }

    public void resetFilters() {
        if (view != null) {
            categorySpinner.setSelection(0);
            productSpinner.setSelection(0);
            priceSpinner.setSelection(0);
        }
    }
    // some more codes here
}

My Mainactivity:

public class MainActivity extends AppCompatActivity {


    private FilterDialogFragment filterDialog;
    private Button button_clear;
    private Button button_filter;


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

        button_clear = findViewById(R.id.button_clear);
        button_filter = findViewById(R.id.button_filter);

        filterDialog = new FilterDialogFragment();

        button_filter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Show the dialog containing filter options
                filterDialog.show(getSupportFragmentManager(), FilterDialogFragment.TAG);
            }
        });

        button_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //reset all filters
                filterDialog.resetFilters();
            }
        });

        //some more codes here
    }
    //some more methods here
}

But by clicking the button that opens the Dialogfragment, the values of the Spinners stay the same instead of returning the data of position 0 of each spinner.

Would anyone know how to fix it? I’ve tried everything and I can’t.

1 answer

0


A simple way that I ended up finding was to remove the resetFilters method in Filterdialogfragment and on the Mainactivity button to instantiate a new Dialogfragment.

 button_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //reset all filters
                filterDialog = new FilterDialogFragment();          
      }
        });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.