我有一个DatePicker
,我正在尝试按如下方式对其进行初始化:
DatePicker dp_up = (DatePicker) findViewById(R.id.datePicker);
String inputPattern = "MMM dd, yyyy";
String outputPattern = "dd/MM/yyyy";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String str = null;
try {
date = inputFormat.parse(GDate);
str = outputFormat.format(date);
String Astr[] = str.split("/");
int myday = Integer.parseInt(Astr[0]);
int mymonth = Integer.parseInt(Astr[1]);
int myyear = Integer.parseInt(Astr[2]);
**dp_up.updateDate(myyear, mymonth-1, myday);**
OR
**dp_up.init(myyear, mymonth-1, myday,null);**
} catch (ParseException e) {
e.printStackTrace();
}
我的变量包含它们的int值,但它会一直显示当前日期而不是我想要的日期。
日期选择器的XML是
<DatePicker
android:layout_width="match_parent"
android:layout_height="96dp"
android:id="@+id/datePicker"
android:layout_gravity="center"
android:calendarViewShown="false"
android:spinnersShown="true"
android:layout_margin="5dp"
android:datePickerMode="spinner"
android:measureAllChildren="false"
android:padding="2dp" />
提前致谢。
答案 0 :(得分:0)
我相应地使用下面的代码,它工作正常。我把它放在setContentView之后的onCreate中。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatePicker dp_up = (DatePicker) findViewById(R.id.datePicker);
String inputPattern = "MMM dd, yyyy";
String outputPattern = "dd/MM/yyyy";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String str = null;
try {
String GDate = "Oct 21, 2016";
date = inputFormat.parse(GDate);
str = outputFormat.format(date);
String Astr[] = str.split("/");
int myday = Integer.parseInt(Astr[0]);
int mymonth = Integer.parseInt(Astr[1]);
int myyear = Integer.parseInt(Astr[2]);
dp_up.updateDate(myyear, mymonth-1, myday);
} catch (ParseException e) {
e.printStackTrace();
}
}
我的布局如下
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.elyeproj.myapplication.MainActivity">
<DatePicker
android:id="@+id/datePicker"
android:layout_width="match_parent"
android:layout_height="match_parent"></DatePicker>
</RelativeLayout>
您可以尝试使用此代码,看看它是否有效?我在Nexus 5仿真器设备上试用了Android M。
答案 1 :(得分:0)
我已将datePicker Listener定义为
dp.init(year, month, day, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {}
我的代码之后的几行,它总是得到当前日期所以我放了一个变量标志来区分新的条目或更新