我有一个拉出DatePicker片段的按钮,但我无法弄清楚如何根据所选日期更改视图。我在我的main.java中放置了onDateSet方法,这是调用片段的活动,意图改变了这个方法中的视图,但是当日期改变并且我不确定我做错了什么时它什么也没做。
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
}
我的MainScreen.java是
public class MainScreen extends FragmentActivity implements DatePickerDialog.OnDateSetListener {
static final int DATE_DIALOG_ID = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
}
public void showDatePickerDialog(View v) {
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
Intent intent = new Intent(this, January_1.class);
startActivity(intent);
}
}
答案 0 :(得分:1)
您应该在DatePickerFragement中使用onDateSet()
侦听器:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Activity activity = getActivity();
Intent intent = new Intent(activity, January_1.class);
activity.startActivity(intent);
}
}
从评论中添加
您使用monthOfYear
的错误索引,来自the documentation:
monthOfYear 为了与Calendar兼容而设置的月份(0-11)。
所以1月是0
,2月是1
等等
为了限制任何混淆,我建议使用Calendar类中的月份名称和switch语句:
Intent intent;
switch(monthOfYear) {
case Calendar.JANUARY:
intent = new Intent(activity, January_1.class);
break;
case Calendar.FEBRUARY:
// etc...
}
activity.startActivity(intent);