我是android新手,我想在TextView上显示单击对话框的日期选择器。但是,在textview上设置datepicker的日期需要两次。
TextView XML:
<TextView
android:id="@+id/dateTxtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="MM/DD/YYYY">
活动代码:
private static final String TAG = "MainActivity";
private TextView mDisplayDate;
private DatePickerDialog.OnDateSetListener mDateSetListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setting date at the start of the app
mDisplayDate = (TextView) findViewById(R.id.dateTxtView);
mDisplayDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCalendar = Calendar.getInstance();
int year = mCalendar.get(Calendar.YEAR);
int month = mCalendar.get(Calendar.MONTH);
int day = mCalendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dateDialog = new DatePickerDialog(
MainActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day
);
dateDialog.setTitle("Select the date");
dateDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dateDialog.show();
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
Log.d(TAG,"date has been set");
String dateToday = month + "/" + dayOfMonth + "/" + year;
mDisplayDate.setText(dateToday);
}
};
}
});
首先,我单击textview并显示对话框datepicker,并在设置日期后单击Ok,没有值传递给textview。在第二次,我再次点击并设置另一个日期,日期现在传递到textview。请帮我解决问题。
答案 0 :(得分:0)
您应该声明并定义您的监听器
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
month = month + 1;
Log.d(TAG,"date has been set");
String dateToday = month + "/" + dayOfMonth + "/" + year;
mDisplayDate.setText(dateToday);
}
};
在Picker构造函数中使用它之前
DatePickerDialog dateDialog = new DatePickerDialog(
MainActivity.this,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year,month,day
);
答案 1 :(得分:0)
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
mDateSetListener = (datePicker, year1, month1, day1) -> {
cal.set(year1, month1, day1);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy", Locale.getDefault());
((IconButtonPlaceHolder) mRelatedView).setText(simpleDateFormat.format(cal.getTime()));
};
DatePickerDialog dialog = new DatePickerDialog(
activity,
android.R.style.Theme_Holo_Light_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();