android – 在片段中实现DatePicker

前端之家收集整理的这篇文章主要介绍了android – 在片段中实现DatePicker前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Fragment,它是片段的实例,而不是DialogFragment.

我做过google的大部分搜索结果显示如何使用DialogFragment来拥有DatePicker.

这在我的情况下不起作用,因为Fragment和DialogFragment的类型不匹配

任何一个例子或想法都是有帮助的

这是片段Java代码

public class CreateReportFragment extends Fragment {

        public CreateReportFragment(){}

        public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) 
        {

               rootView = inflater.inflate(R.layout.activity_create_report,container,false);
               initViews();
               return rootView;
        }

        private void initViews() 
       {

         final Calendar c = Calendar.getInstance();
             year  = c.get(Calendar.YEAR);
             month = c.get(Calendar.MONTH);
             day   = c.get(Calendar.DAY_OF_MONTH);

             editTextDate.setText(new StringBuilder()
             // Month is 0 based,just add 1
             .append(year)
             .append("-")
                    .append(month + 1)
                     .append("-").append(day));

        buttonDate = (Button)rootView.findViewById(R.id.buttonDate);
        }

如何在片段中实现DatePicker?

解决方法

使用DialogFragment

如果我猜对了,你想要点击buttonDate显示一个DatePicker

http://developer.android.com/guide/topics/ui/controls/pickers.html

点击按钮

DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(),"datePicker");

DatePickerFragment.java

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 view,int year,int month,int day) {
Calendar c = Calendar.getInstance();
c.set(year,day);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(c.getTime());    
}
}

猜你在找的Android相关文章