【代码段】Android Studio使用DatePicker选择日期
布局文件中放一个TextView
就好了
Java文件如下:
public class TestDatePickerActivity extends AppCompatActivity {
private static final String TAG = "TestDatePickerActivity";
private TextView mDatePicker;
private DatePickerDialog.OnDateSetListener mDateSetListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_date_picker);
mDatePicker = findViewById(R.id.tv_datepicker);
mDatePicker.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(
TestDatePickerActivity.this,
android.R.style.Theme_Holo_Dialog_MinWidth,
mDateSetListener,
year, month, day);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
});
mDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Log.d(TAG, "onDateSet: date: " + year + "/" + month + "/" + dayOfMonth);
int rm = month + 1;
mDatePicker.setText(year + "/" + rm + "/" + dayOfMonth);
}
};
}
}
Listen to your heart.