材質 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;
}
}
輸出: