简体   繁体   English

从班级到活动的数据传输

[英]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. 我刚开始在Android中,我有一个具有类(扩展DialogFragment)和活动的程序。 How can data be sent from the class to activity in android so that it can be displayed? 如何将数据从类发送到android中的活动,以便可以显示? 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? 我还有一个问题:在Android开发中应该在哪里进行计算? Let's suppose i need to do some heavy calculations with the hourOfDay before i display the results. 假设我需要在显示结果之前对hourOfDay进行大量计算。 Should it be done in the MyDialogFragment class (so my activities are only used for displaying the results, nothing more)? 是否应该在MyDialogFragment类中完成(所以我的活动仅用于显示结果,仅此而已)?

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. 您可能应该将其保留在适当的片段中,除非您的Activity要使用的多个片段都需要它。 If it's intensive, get it off the UI thread by using Loaders . 如果需要大量资源,请使用Loaders将其从UI线程中删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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