DatepickerDialog日期选择器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/laptoper/article/details/47116115

对我有帮助的博客点击打开链接这个真的不难,看别人的教程就ok了,我就贴个代码。

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnDate = (Button) findViewById(R.id.btnDate);
        btnDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCreateDialog().show();//直接调用下面的函数就可以弹出日期选择框
            }
        });
    }
    protected Dialog onCreateDialog(){
        Calendar calendar = Calendar.getInstance();
        Dialog dialog = null;
                DatePickerDialog.OnDateSetListener dateListener =
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker datePicker,
                                                  int year, int month, int dayOfMonth) {
                                EditText editText =
                                        (EditText) findViewById(R.id.editText);
                                //Calendar月份是从0开始,所以month要加1
                                editText.setText(  year + "-" +
                                        (month+1) + "-" + dayOfMonth );
                            }
                        };
                dialog = new DatePickerDialog(this,
                        dateListener,
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
        return dialog;
    }

再贴一个布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button android:id="@+id/btnDate"
            android:text="日期选择"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <EditText android:id="@+id/editText"
            android:layout_width="250px"
            android:layout_height="wrap_content"
            android:editable="false"
            android:cursorVisible="false"/>
    </LinearLayout>
</RelativeLayout>


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页