简体   繁体   中英

Data transfer from class to activity

Hi!

I'm just starting out in Android i have a program that has a class (extending DialogFragment) and an activity. How can data be sent from the class to activity in android so that it can be displayed? I tried it through setters, but i'm not sure if this is the right way to go?

public class MyDialogFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current time as the default values for the picker
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);

            // Create a new instance of TimePickerDialog and return it
            return new TimePickerDialog(getActivity(), this, hour, minute,
                    DateFormat.is24HourFormat(getActivity()));
        }

        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // Do something with the time chosen by the user
            MainActivity main = new MainActivity();
            main.setHour(hourOfDay); // SETTER METHOD HERE.  
        }

}

I have one more question actually: where should the calculations be done in android development? Let's suppose i need to do some heavy calculations with the hourOfDay before i display the results. Should it be done in the MyDialogFragment class (so my activities are only used for displaying the results, nothing more)?

Thank you very much!

You want to do this: Communicating with Activities

All you're doing in the tutorial is implementing an interface with the callbacks you want. So you were almost there.

As far as doing your calculations. You should probably leave that in the appropriate fragment unless multiple fragments your Activity is going to use all need that. If it's intensive, get it off the UI thread by using Loaders .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM