0

У меня есть FragmentDialog внутри которого listener (interface). Мой код.

public class CustomDialogFilterView extends AppCompatDialogFragment {
    List<String> currencies;
    CustomFilterDialogDetailListener listener;
    RecyclerView recyclerView;
    TextView numberOfCurrencies;
    List<Boolean> booleans;
    public CustomDialogFilterView(List<String> currencies, List<Boolean> booleans) {
        this.currencies = currencies;
        this.booleans = booleans;
    }
    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();

        View view = inflater.inflate(R.layout.custom_filter_dialog_layout, null);
        builder.setView(view)
                .setTitle("Filter")
                .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        listener.applyData();
                    }
                });
        recyclerView = view.findViewById(R.id.filter_recycler_view);
        numberOfCurrencies = view.findViewById(R.id.count_currencies);
        LinearLayoutManager llm = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(llm);
        RecyclerFilterViewAdapter adapter = new RecyclerFilterViewAdapter(currencies, booleans);
        recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.HORIZONTAL));
        recyclerView.setAdapter(adapter);
        return builder.create();
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        Fragment parent = getParentFragment();
        if (parent != null){
            try {
                listener = (CustomFilterDialogDetailListener) parent;
            } catch (ClassCastException e){
                throw  new ClassCastException(e.getMessage() + " must implement CustomFilterDialogDetailListener");
            }
        } else {
            try {
                listener = (CustomFilterDialogDetailListener) context;
            } catch (ClassCastException e){
                throw  new ClassCastException(e.getMessage() + " must implement CustomFilterDialogDetailListener");
            }
        }
    }
    public interface  CustomFilterDialogDetailListener{
        void applyData();
    }
}

По нажатию на кнопку ок у меня срабатывает listener.

Все это работает когда я имплементирую метод слушателя внутри активити.

Но когда я делаю тоже самое внутри фрагмента срабатывает ClassCastException

CustomDialogFilterView filterView = new CustomDialogFilterView(allExchangeCurrencies, selBool);
filterView.show(getParentFragmentManager(), "example");

Я не знаю правильно ли я передаю аргументы метода show. Когда я удаляю listener CustomDialog запускается. Подскажите пожалуйста, что я делаю не так? Заранее благодарю!

1 ответ 1

0

Можно например использовать onActivityResult(). Для этого в месте где вам нужно отправить данные делаем такую отправку (например):

Intent i = new Intent();
i.putExtra("test","test");
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);

и ловим данные:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
        case DATEPICKER_FRAGMENT:
            if (resultCode == Activity.RESULT_OK) { 
                Bundle bundle=data.getExtras();
                String test = bundle.getString("test","error");
                EditText editText = (EditText) getView().findViewById(R.id.foodDeliveryDateFiled);
                editText.setText(test);
            }
            break;
    }

пример на котлине(отправка):

val intent = Intent()
intent.putExtra("test", "test")
targetFragment!!.onActivityResult(0, Activity.RESULT_OK, intent)
Objects.requireNonNull<FragmentManager>(fragmentManager).beginTransaction().remove(this).commitAllowingStateLoss()

пример на котлине (прием):

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
        
            0 -> {
                if (resultCode == Activity.RESULT_OK) {
                    if (data != null) {
                        val data = data.getStringExtra("test", "error")
                       

                    }
                }
            }

        }
    }

UPDATE

Вот как создать фрагмент:

val filterScr = NotesFilter()
val bundle = Bundle()
bundle.putString("test", "test")

filterScr.arguments = bundle

filterScr.setTargetFragment(this, 1)
val ft = Objects.requireNonNull<FragmentManager>(fragmentManager).beginTransaction()
filterScr.show(ft, filterScr.TAG)
3
  • метод onActivityResult где мы получаем данные понятно. Но непонятно одно, вместо конструктора где я вызываю диалогФрагмент мне нужно отправить данные через интент ??? Диалог нужно вызвать методом show?
    – Koki9595
    2 сен 2020 в 17:34
  • да, это обычный диалог фрагмент) приложил код для вызова такого фрагмента, не очень понял про интент при вызове диалога. для передачи данных я использую бандл и туда ложить можно то же самое что и в интент
    – Andrew
    2 сен 2020 в 17:47
  • Огромное спасибо!!!
    – Koki9595
    2 сен 2020 в 18:25

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.