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());    
}
}

相关文章

以下为个人理解,如错请评 CE: 凭据加密 (CE) 存储空间, 实际路径/data/user_ce/ DE: 设备加密 (DE) 存...
转载来源:https://blog.csdn.net/yfbdxz/article/details/114702144 用EventLog.writeEvent打的日志(或...
事件分发机制详解 一、基础知识介绍 1、经常用的事件有:MotionEvent.ACTION_DOWN,MotionEvent.ACTION...
又是好久没有写博客了,一直都比较忙,最近终于有时间沉淀和整理一下最近学到和解决的一些问题。 最近进...
Android性能优化——之控件的优化 前面讲了图像的优化,接下来分享一下控件的性能优化,这里主要是面向...
android的开源库是用来在android上显示gif图片的。我在网上查了一下,大家说这个框架写的不错,加载大的...