Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

android - Retrieve and set data from DialogFragment (DatePicker)

My DialogFragment class is invoked when I press a button on a activity. I want the date set through this DialogFragment to be displayed on the buttons text. FindViewById refuses to be recognized by the class.

I found a similar question but I'm unable to relate it to my case.

Code:

  1. Button which calls the Dialogue fragment:

    public void datepicker(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getFragmentManager(), "datePicker"); 
    }
    
  2. Code for dialogue fragment:

    public class DatePickerFragment extends DialogFragment implements
        DatePickerDialog.OnDateSetListener {
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceSateate) {
    
            final Calendar c = Calendar.getInstance();
                int year = c.get(Calendar.YEAR);
                int month = c.get(Calendar.MONTH);
                int day = c.get(Calendar.DAY_OF_MONTH);
    
                return new DatePickerDialog(getActivity(), this, year, month, day);
            }
    
            public void onDateSet(DatePicker view, int year, int month, int day) {
                // Do something with the date chosen
            }
        }
    }
    
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the method in your DialogFragment that is in charge of being notified when the user sets the date, do this

Button activityButton = (Button)getActivity().findViewById(R.id.myButton);
activityButton.setText (myDate);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...