[英]How to create a DatePicker from class which do not extends Activity, Android?
I'm trying to create DatePicker dialog from a class that doesn't extends the Activity class. 我正在尝试从不扩展Activity类的类创建DatePicker对话框。 I need DatePicker in a class called EnterDate which has Context attribute containing Activity Context. 我在名为EnterDate的类中需要DatePicker,该类的Context属性包含Activity Context。
All examples of DatePicker on the WEB are basic ones written in Activity class and that's why they confusing me. WEB上所有DatePicker的示例都是用Activity类编写的基本示例,这就是为什么它们使我感到困惑。
I want date picker which works good on Android lower then 3.0. 我想要日期选择器,它在低于3.0的Android平台上运行良好。 I don't use XML layout. 我不使用XML布局。
So basically I need suggestion where to put onCreateDialog() , how to retrieve chosen time, etc. 所以基本上我需要建议在哪里放置onCreateDialog(),如何检索选择的时间等。
I've Button which have onClickListener() for calling a DatePicker. 我有Button,它具有用于调用DatePicker的onClickListener()。
An hour ago I've asked a same question for the TimePicker and got this answer: How to create a TimePicker from class which do not extends Activity, Android? 一个小时前,我对TimePicker提出了相同的问题,并得到了以下答案: 如何从不扩展Activity(Android)的类中创建TimePicker?
I assume that that solution needs only minor modification to work like DatePicker.. 我认为该解决方案只需要进行较小的修改即可像DatePicker一样工作。
Tnx 特纳克斯
modified class 修改类
public class MyDatePicker {
DatePickerDialog mDatePickerDialog;
public interface onDateSet {
public void onDate(DatePicker view, int year, int monthOfYear,
int dayOfMonth);
}
onDateSet mOnDateSet;
public void setDateListener(onDateSet mOnDateSet) {
this.mOnDateSet = mOnDateSet;
}
public MyDatePicker(Context ctx) {
mDatePickerDialog = new DatePickerDialog(ctx, new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mOnDateSet.onDate(view, year, monthOfYear, dayOfMonth);
}
}, 2000, 1, 1);
}
public void show() {
mDatePickerDialog.show();
}
and.. 和..
public void ShowDatePicker() {
MyDatePicker myTimePicker = new MyDatePicker(this);
myTimePicker.show();
myTimePicker.setDateListener(new onDateSet() {
@Override
public void onDate(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Toast.makeText(MainActivity.this,
"date is " + year + ":" + monthOfYear+":"+dayOfMonth,
Toast.LENGTH_LONG).show();
}
});
}
You do not need activity for creating and showing dialog. 您不需要创建和显示对话框的活动。 You can just create Dialog with callback and init data with helper class DatePickerDialog.Builder
, and then call show()
for this builder. 您可以使用帮助程序类DatePickerDialog.Builder
创建带有回调和初始化数据的Dialog,然后为该构建器调用show()
。
This will work only if you are in UI thread. 仅当您在UI线程中时,这才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.