Send Data from DialogFragment to Fragment

前端 未结 3 1603
花落未央
花落未央 2021-01-22 08:06

I have a fragment which contain an EditText when I click on that EditText a DatePicker Dialog appears to select date.
FragmentFile

public c         


        
3条回答
  •  清歌不尽
    2021-01-22 08:56

    I have sloved the problem thank's to this topic, the seconde response of topic.
    DatePickerFragment.java

    @Override
        public void onDateSet(DatePicker view, int year, int month, int day) {
            Calendar c = Calendar.getInstance();
            c.set(year, month, day);
    
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            String formattedDate = sdf.format(c.getTime());
            // in this part I stored the selected date into the intent
            Intent i = new Intent();
            i.putExtra("selectedDate",formattedDate);
            getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
        }
    

    Fragment File

    public static final int DATEPICKER_FRAGMENT=1; // adding this line
    @Override
    
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_feeding, container, false);
        EditText editText = (EditText) view.findViewById(R.id.foodDeliveryDateFiled);
    
        editText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment picker = new DatePickerFragment();
                picker.setTargetFragment(FeedingFragment.this, DATEPICKER_FRAGMENT);
                picker.show(getFragmentManager().beginTransaction(), "Date Picker");
            }
        });
        return view;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch(requestCode) {
            case DATEPICKER_FRAGMENT:
                if (resultCode == Activity.RESULT_OK) {
                    // here the part where I get my selected date from the saved variable in the intent and the displaying it.
                    Bundle bundle=data.getExtras();
                    String resultDate = bundle.getString("selectedDate","error");
                    EditText editText = (EditText) getView().findViewById(R.id.foodDeliveryDateFiled);
                    editText.setText(resultDate);
                }
                break;
        }
    

提交回复
热议问题