1

我有两个 ImageButton。一个负责设置开始日期,另一个负责设置结束日期。当每一个被按下时,它们都会显示一个 DatePickerDialog。onCreateDialog 方法在另一个类中。这是那个类:

日期选择器片段.Java

package com.ThatOneNoob.smarthaul;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.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);
}


@Override
public void onDateSet(DatePicker v, int year, int month, int day) {
    // TODO Auto-generated method stub

    switch (v.getId()){

    case R.id.datesel1:
        toDate.setText(new StringBuffer());
    }
 }


}

显然不完整,toDate 是它应该管理的 TextView 之一。datesel1 是 ImageButton。它将附加 TextView 以包含 01/02/2013 格式的设置日期。我不能将 TextView 声明为静态的,所以我不能在此类中调用它。那么,我应该让 onDateSet 调用一个静态方法,将 TextView 设置为它需要做的事情吗?或者我应该怎么做?

4

1 回答 1

5

在单独的类中创建对话框并为侦听器创建一个 getter:

public class DatePickerFragment extends DialogFragment
{
    private OnDateSetListener onDateSetListener;

    public DatePickerFragment() {}

    public void setOnDateSetListener(OnDateSetListener onDateSetListener) {
        this.onDateSetListener = 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(), onDateSetListener, year, month, day);
    }

}

DatePickerDialog.OnDateSetListener 的实现在您引用 TextView 的其他片段的活动中进行。
然后创建一个日历并使用SimpleDateFormat,看一个例子

public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, monthOfYear, dayOfMonth);
    <=== YOUR SETTEXT TO YOUR TEXTVIEW HERE ===>
}
于 2013-06-03T17:10:28.513 回答