Created
June 10, 2020 09:47
-
-
Save harish81/7aa4bc1880f8e4a4f6faee186ad099b0 to your computer and use it in GitHub Desktop.
DatePicker EditText in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.DatePickerDialog; | |
import android.content.Context; | |
import android.graphics.Canvas; | |
import android.util.AttributeSet; | |
import android.view.View; | |
import android.widget.DatePicker; | |
import androidx.appcompat.widget.AppCompatEditText; | |
import java.text.SimpleDateFormat; | |
import java.util.Calendar; | |
import java.util.Date; | |
public class DatePickerEditText extends AppCompatEditText { | |
private Calendar calendar; | |
public DatePickerEditText(Context context) { | |
this(context, null); | |
} | |
public DatePickerEditText(Context context, AttributeSet attrs) { | |
this(context, attrs, androidx.appcompat.R.attr.editTextStyle); | |
} | |
public DatePickerEditText(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
calendar = Calendar.getInstance(); | |
configureListeners(); | |
} | |
@Override | |
protected void onDraw(Canvas canvas) { | |
super.onDraw(canvas); | |
setFocusable(false); | |
setClickable(true); | |
} | |
private void configureListeners() { | |
setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
openDatePicker(); | |
} | |
}); | |
} | |
private void openDatePicker() { | |
new DatePickerDialog(this.getContext(), | |
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); | |
Date date1 = calendar.getTime(); | |
DatePickerEditText.this.setText(new SimpleDateFormat("yyyy-MM-dd").format(date1)); | |
} | |
}, | |
calendar.get(Calendar.YEAR), | |
calendar.get(Calendar.MONTH), | |
calendar.get(Calendar.DAY_OF_MONTH) | |
).show(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<com.google.android.material.textfield.TextInputLayout | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content"> | |
<com.your-package-name.DatePickerEditText | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:hint="Date Of Birth" /> | |
</com.google.android.material.textfield.TextInputLayout> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment