android使用1个日期选择器为不同的文本字段

时间:2014-02-02 09:29:39

标签: android

android ...如何在点击不同的文本视图时使用日期选择器在单击的文本视图中显示所选日期..我在成功中尝试了切换和点击监听器...仅用于1个文本视图工作如下

enter code here
public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment() ;
    newFragment.show(getSupportFragmentManager(), "datePicker");
}





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 month, int day) {
        // display selected date in s-fire

        TextView sfire = (TextView) findViewById(R.id.fire);

        Date d = new Date(year - 1900, month, day);
        String sDate = new SimpleDateFormat("dd/MM/yyyy").format(d);
        sfire.setText(sDate.toString());

        Log.d("hello", sDate.toString());
    }



}

1 个答案:

答案 0 :(得分:2)

目前,您的日期选择器片段仅适用于您正在保存数据的TextView:

TextView sfire = (TextView) findViewById(R.id.fire);

您可以将TextView的id作为参数传递给片段,然后将日期添加到指定的id:

public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment() ;
    Bundle args = new Bundle();
    args.putInt("id", R.id.fire);
    newFragment.show(getSupportFragmentManager(), "datePicker");
}


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 month, int day) {
        // display selected date in s-fire

        TextView sfire = getArguments().getInt("id");    

        Date d = new Date(year - 1900, month, day);
        String sDate = new SimpleDateFormat("dd/MM/yyyy").format(d);
        sfire.setText(sDate.toString());

        Log.d("hello", sDate.toString());
    }

}