如何在Fragment中使用DialogFragment作为日期选择器(未使用onCreateDialog)

时间:2016-04-22 02:17:18

标签: android android-fragments android-studio android-dialogfragment

我在DialogFragment中做了一些研究,并使用片段作为onCreate Dialog不起作用。我知道有这个文档

http://developer.android.com/reference/android/app/DialogFragment.html#AlertDialog

虽然我是Android编程的新手,但要理解所涉及的代码并不容易,除非它与我正在做的事情有关,下面是我遇到的问题:

public class AddFixture extends Fragment {

 public AddFixture() {

 }

 private DatePicker datePicker;
 private Calendar calendar;
 private TextView dateView;
 private int year, month, day;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setHasOptionsMenu(true);
 }

 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
  Bundle savedInstanceState) {
  // Inflate the layout for this fragment
  return inflater.inflate(R.layout.add_fixture, container, false);
 }

 @Override
 public void onViewCreated(View view, Bundle savedInstanceState) {

  add_date = (Button) view.findViewById(R.id.dateButton);

  dateView = (TextView) view.findViewById(R.id.dateSelected);
  calendar = Calendar.getInstance();

  year = calendar.get(Calendar.YEAR);
  month = calendar.get(Calendar.MONTH);
  day = calendar.get(Calendar.DAY_OF_MONTH);
  showDate(year, month + 1, day);

  //call setDate method
  setDate();


  @SuppressWarnings("deprecation")
  public void setDate() {
   add_date.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     getActivity().showDialog(999);
     Toast.makeText(getActivity().getApplicationContext(), "ca", Toast.LENGTH_SHORT)
      .show();
    }
   });
  }

  //onCreateDialog depreciated
  @Override
  protected Dialog onCreateDialog(int id) {
   // TODO Auto-generated method stub
   if (id == 999) {
    return new DatePickerDialog(getActivity(), myDateListener, year, month, day);
   }
   return null;
  }

  private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
   @Override
   public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
    // TODO Auto-generated method stub
    // arg1 = year
    // arg2 = month
    // arg3 = day
    showDate(arg1, arg2 + 1, arg3);
   }
  };

  private void showDate(int year, int month, int day) {
   dateView.setText(new StringBuilder().append(day).append("/")
    .append(month).append("/").append(year));
  }


  @Override
  public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
   getActivity().getMenuInflater().inflate(R.menu.main, menu);
   super.onCreateOptionsMenu(menu, inflater);
  }

 }

0 个答案:

没有答案