MainActivity中的按钮,在DialogFragment中重置微调器

时间:2019-03-21 15:58:21

标签: java android android-layout dialog spinner

我在MainActivity中有两个按钮,第一个按钮打开一个带有一些微调器的自定义DialogFragment,在另一个按钮中,它重置此DialogFragment的微调器。

当我单击重置按钮时,它将调用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
}

我的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
}

但是,通过单击打开DialogFragment的按钮,微调器的值保持不变,而不是返回每个微调器位置0的数据。

有人知道如何解决吗?我已经尝试了一切,但不能。

1 个答案:

答案 0 :(得分:0)

我最终找到的最简单的方法是删除resetFilters方法,而是这样做了:

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