我正在创建一个需要从user获取日期的android活动。我的活动在触摸时有一个编辑文本显示了datepicker对话框并在编辑文本中显示了日期。我已经使用Datepickerdialog完成了它。我的问题当我点击edittext 2时会显示datepickerdialog。
这是我的代码......
Activity.class
EditText startDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_event);
startDate= (EditText) findViewById(R.id.startdate);
startDate.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
new DatePickerDialogFragment().show(getFragmentManager(),"DatePicker");
return true;
}
});
}
@Override
public void returnDate(String date) {
startDate.setText(date);
}
DatepickerDialog类
public class DatePickerDialogFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
TheListener listener;
public interface TheListener{
public void returnDate(String date);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar calendar=Calendar.getInstance();
int year=calendar.get(Calendar.YEAR);
int month=calendar.get(Calendar.MONTH);
int day=calendar.get(Calendar.DAY_OF_MONTH);
listener = (TheListener) getActivity();
return new DatePickerDialog(getActivity(),this,year,month,day);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar c=Calendar.getInstance();
c.set(year,monthOfYear,dayOfMonth);
SimpleDateFormat dateFormat=new SimpleDateFormat("dd-MM-yyyy");
String date=dateFormat.format(c.getTime());
if(listener!=null)
{
listener.returnDate(date);
}
}
}
我的代码中有什么问题。以及如何解决它。
答案 0 :(得分:2)
使用ACTION_UP
动作事件
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
new DatePickerDialogFragment().show(getFragmentManager(),"DatePicker");
}
return false;
}
答案 1 :(得分:0)
我通过仅添加条件hasFocus
然后调用该方法解决了此问题。它解决了我的问题。
在XML部分中:我将属性添加到EditText:
android:focusable="false"
在主活动中的onCreate方法下:
dateinput.setInputType(InputType.TYPE_NULL); //keyboard disappear
dateinput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showDateDailogForm(dateinput);
}
}
});
在onCreate方法之外的主活动中:
private void showDateDailogForm(final EditText dateinput) {
Calendar calendar = Calendar.getInstance();
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateinput.setText(simpleDateFormat.format(calendar.getTime()));
}
};
new DatePickerDialog(MainActivity.this, dateSetListener, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}