首先贴上布局文件的代码,我们需要一个Button和一个EditText控件,注意这里的android:focusable=”false”是指EditText不可编辑
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.yuejian5.activity.ActivityDetailActivity">
<EditText
android:id="@+id/date"
android:hint="日期"
android:focusable="false"
android:layout_marginLeft="38dp"
android:layout_width="wrap_content"
android:layout_height="50dp" />
<Button
android:text="选择日期"
android:id="@+id/choose"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</LinearLayout>
下面是Activity中的代码
public class ActivityDetailActivity extends BaseActivity {
private int mYear;
private int mMonth;
private int mDay;
private EditText tv_data;
private Button choose;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
tv_data = (EditText) findViewById(R.id.date);
choose = (Button) findViewById(R.id.choose);
Calendar ca = Calendar.getInstance();
mYear = ca.get(Calendar.YEAR);
mMonth = ca.get(Calendar.MONTH);
mDay = ca.get(Calendar.DAY_OF_MONTH);
choose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO 调用时间选择器
new DatePickerDialog(ActivityDetailActivity.this, onDateSetListener, mYear, mMonth, mDay).show();
}
});
}
private DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
String days;
if (mMonth + 1 < 10) {
if (mDay < 10) {
days = new StringBuffer().append(mYear).append("年").append("0").
append(mMonth + 1).append("月").append("0").append(mDay).append("日").toString();
} else {
days = new StringBuffer().append(mYear).append("年").append("0").
append(mMonth + 1).append("月").append(mDay).append("日").toString();
}
} else {
if (mDay < 10) {
days = new StringBuffer().append(mYear).append("年").
append(mMonth + 1).append("月").append("0").append(mDay).append("日").toString();
} else {
days = new StringBuffer().append(mYear).append("年").
append(mMonth + 1).append("月").append(mDay).append("日").toString();
}
}
tv_data.setText(days);
}
};
}
看一下我们的效果图
这样我们的日期选择功能就做好了