材质 DatePicker
将以下依赖项添加到依赖项部分中的 build.gradle
文件。 (这是日期选择器的非官方库)
compile 'com.wdullaer:materialdatetimepicker:2.3.0'
现在我们必须在 Button click 事件上打开 DatePicker
。
所以在 xml 文件上创建一个 Button,如下所示。
<Button
android:id="@+id/dialog_bt_date"
android:layout_below="@+id/resetButton"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textColor="#FF000000"
android:gravity="center"
android:text="DATE"/>
并且在 MainActivity 中使用这种方式。
public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener{
Button button;
Calendar calendar ;
DatePickerDialog datePickerDialog ;
int Year, Month, Day ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendar = Calendar.getInstance();
Year = calendar.get(Calendar.YEAR) ;
Month = calendar.get(Calendar.MONTH);
Day = calendar.get(Calendar.DAY_OF_MONTH);
Button dialog_bt_date = (Button)findViewById(R.id.dialog_bt_date);
dialog_bt_date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
datePickerDialog = DatePickerDialog.newInstance(MainActivity.this, Year, Month, Day);
datePickerDialog.setThemeDark(false);
datePickerDialog.showYearPickerFirst(false);
datePickerDialog.setAccentColor(Color.parseColor("#0072BA"));
datePickerDialog.setTitle("Select Date From DatePickerDialog");
datePickerDialog.show(getFragmentManager(), "DatePickerDialog");
}
});
}
@Override
public void onDateSet(DatePickerDialog view, int Year, int Month, int Day) {
String date = "Selected Date : " + Day + "-" + Month + "-" + Year;
Toast.makeText(MainActivity.this, date, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.abc_main_menu, menu);
return true;
}
}
输出: