1. 程式人生 > >Android:DatePicker日期選擇器

Android:DatePicker日期選擇器

1.佈局一個按鈕,用於啟動日期選擇器

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="zs.recyclerviewdemo.ChooseDateActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0000-00-00"
        android:id="@+id/btnDate"/>
</LinearLayout>

2.在Activity中啟用DatePicker

public class ChooseDateActivity extends AppCompatActivity {

    private Button btnDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_date);
        btnDate = (Button)findViewById(R.id.btnDate);
        btnDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(ChooseDateActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        String date = year + "-"+ month + "-" + dayOfMonth;
                        btnDate.setText(date);
                    }
                },2018,10,5).show();
            }
        });
    }
}

效果圖: 在這裡插入圖片描述