我通过扩展Fragment创建了一个片段,如下所示:
public class MyFragement extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
return view;
}
我的布局有一个edittext。当我点击edittext时,我想显示datepicker。从日期选择器中选择日期后,所选日期应出现在编辑文本中。
我怎样才能实现这一目标。请帮我一些示例代码。
答案 0 :(得分:3)
你可以在片段类的onCreate中编写这段代码
yourEditText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentDate=Calendar.getInstance();
mYear=mcurrentDate.get(Calendar.YEAR);
mMonth=mcurrentDate.get(Calendar.MONTH);
mDay=mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker=new DatePickerDialog(**YourActivityName**.this, new OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
// TODO Auto-generated method stub
/* Your code to get date and time */
}
},mYear, mMonth, mDay);
mDatePicker.getDatePicker().setCalendarViewShown(false);
mDatePicker.setTitle("Select date");
mDatePicker.show(); }
});
答案 1 :(得分:0)
尝试以下方式:
在onCreatView()之前
/** Callback received when the user "picks" a departure date in the dialog **/
private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
pYear = year;
pMonth = monthOfYear;
pDay = dayOfMonth;
updateDisplay();
}
};
/** Updates the date in the departure date **/
private void updateDisplay() {
dep_date.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(padDate(pDay)).append("/")
.append(padDate(pMonth + 1)).append("/")
.append(pYear).append(" "));
}
在onCreateView()
中EditText dep_date= (EditText ) view.findViewById(R.id.editText1);
/** Listener for click event of the departure date edit text **/
dep_date.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID);
return false;
}
});
OutSide onCreateView()
/** Create a new dialog for date picker */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_DIALOG_ID:
return new DatePickerDialog(this, pDateSetListener, pYear, pMonth, pDay);
}
return null;
}