如何获取从DatePickerFragment
中选择的日期?
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
int Year,Month,Day;
@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);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
}
我希望获取日期的Fragment
并将其设置为文本字段:
public class CalculatorHomeFragment extends Fragment
LinearLayout lyDate;
TextView lblDate;
int Year,Month,Day;
private static CalculatorHomeFragment instance = null;
public CalculatorHomeFragment() {
}
public static CalculatorHomeFragment getInstance() {
if (instance == null)
instance = new CalculatorHomeFragment();
return instance;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_calculator_home, container, false);
lyDate = (LinearLayout) rootView.findViewById(R.id.lyDate);
lblDate = (TextView) rootView.findViewById(R.id.lblDate);
lyDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getActivity().getFragmentManager(), "datePicker");
}
});
return rootView;
}
答案 0 :(得分:0)
你真的不需要第一堂课来获得DataPicker,只需改变你的onClickListener:
lyDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dateDialog= new DatePickerDialog(getActivity(), datePickerListener, mYear, mMonth, mDay);
dateDialog.show();
}
});
在你的类中添加一个OnDateSetListener,如下所示:
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String dateYouChoosed = dayOfMonth + "/" + (monthOfYear + 1) + "/" + year;
lblDate.setText(dateYouChoosed );
}
};