2017-06-22 73 views
0

我設法創建了日期選擇器類,但現在我希望將日期選擇器對話框中的值返回到主活動類。以下是日期選取器對話框的代碼。如何將日期從DatePickerDialog返回到主要活動

public class DateChooser extends DialogFragment implements DatePickerDialog.OnDateSetListener{ 

    public int y,m,d; 

    public Dialog onCreateDialog(Bundle savedInstanceState) 
    { 
     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); 

     return new DatePickerDialog(getContext(),this,year,month,day); 

    } 
    @Override 
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { 
     Toast.makeText(getContext(), "Toast!", Toast.LENGTH_SHORT).show(); 
     setDay(dayOfMonth); 
     setMonth(month); 
     setYear(year); 


    } 

我已經從mainactivity調用這個類。

public void dateSelect(View view) 
{ 
DateChooser dateC = new DateChooser(); 
dateC.show(getSupportFragmentManager(),"tag"); 
} 
+0

從活動或界面調用方法。 – Piyush

+0

請稍微詳細一點。 :) –

回答

0

您可以創建一個界面,例如這樣

public interface DateListener { 
    void onDateSelected(int day, int month, int year); 
} 

,並實現它在你的活動

public class YourActivity extends Activity implements DateListener {...} 

,那麼你必須實現該方法在您的活動......

在你Fragment添加以下字段:

private DateListener dateListener; 

的上一頁|將下載的代碼添加到您的分享標籤:onAttach

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 

    if (!(getActivity() instanceof DateListener)) { 
     throw new ClassCastException("The activity inflating this fragment must implement DateListener!"); 
    } 
    dateListener = (DateListener) getActivity(); 
} 

現在你已經確立了自己的活動爲DateListener,可以用它的DatePicker

+0

onAttach不是活動 – matrix

+0

的方法是true,但您仍然需要它在片段中 - 它在片段附加到活動時調用。在這裏您需要將您的活動設置爲DateListener – Katharina

0
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1); 
int day = datePicker.getDayOfMonth(); 
int month = datePicker.getMonth() + 1; 
int year = datePicker.getYear(); 
String dateInString=year+"-"+month+"-"+day; 
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
Date date = formatter.parse(dateInString); 
System.out.println(date); 
0

結果做到這一點:

一下添加到DateChooser類:

private DateSelectedListener mListener; 

@Override 
public void onDateSet(DatePicker view, int year, int month, int day) { 
    // Do something with the date chosen by the user 
    mListener.onDateSelected(view, year, month, day); 
} 

public void display(FragmentManager manager, String tag, DateSelectedListener listener) { 
    super.show(manager, tag); 
    mListener = listener; 
} 

public interface DateSelectedListener { 
    void onDateSelected(DatePicker view, int year, int month, int day); 
} 

在您的活動中這樣做:

public class MyActivity extends AppCompatActivity implements DateChooser.DateSelectedListener { 
    //onCreate or whatever other method: 
    dateChooser.display(
      getActivity().getSupportFragmentManager(), 
      "datePicker", this); 
} 

祝你好運!!!

相關問題