我的应用程序中有两个日期选择器(fromDate和toDate)。当用户从这两个日期选择器中选择并设置两个日期时,我希望我的应用程序在另一个编辑文本(天)框中自动显示它们之间的天数。
我该怎么做?
答案 0 :(得分:1)
首先为两个日期选择器添加 OnDateChangedListener
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
fromDate.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
UpdateText();
}
});
toDate.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
UpdateText();
}
});
创建一个函数 UpdateText 以更新EditText天
private void UpdateText() {
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
localCalendar.set(fromDate.getYear(), fromDate.getMonth(), fromDate.getDayOfMonth());
int day1 = localCalendar.get(Calendar.DAY_OF_YEAR);
localCalendar.set(toDate.getYear(), toDate.getMonth(), toDate.getDayOfMonth());
int day2 = localCalendar.get(Calendar.DAY_OF_YEAR);
int day = day2-day1;
days.setText(""+day);
}
注意:确保导入正确的文件
import java.util.Calendar;
import java.util.TimeZone;
完成计划
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;
import java.util.TimeZone;
public class MainActivity extends AppCompatActivity {
DatePicker fromDate, toDate;
EditText days;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fromDate = (DatePicker) findViewById(R.id.datePicker1);
toDate = (DatePicker) findViewById(R.id.datePicker2);
days = (EditText)findViewById(R.id.Days);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
fromDate.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
UpdateText();
}
});
toDate.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
UpdateText();
}
});
}
private void UpdateText() {
Calendar localCalendar = Calendar.getInstance(TimeZone.getDefault());
localCalendar.set(fromDate.getYear(), fromDate.getMonth(), fromDate.getDayOfMonth());
int day1 = localCalendar.get(Calendar.DAY_OF_YEAR);
localCalendar.set(toDate.getYear(), toDate.getMonth(), toDate.getDayOfMonth());
int day2 = localCalendar.get(Calendar.DAY_OF_YEAR);
int day = day2-day1;
days.setText(""+day);
}
}