Reputation: 85
I want to put the DatePicker's Date in an EditText and keep updating this edittext as the person changes the date. Someone help me?
this is my code:
private View view;
private Button next;
private EditText birthday;
private DatePicker datePicker;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_birthday, container, false);
initWidgets();
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();
birthday.setText(day + "/" + month + "/" + year);
return view;
}
private void initWidgets() {
next = view.findViewById(R.id.bt5);
birthday = view.findViewById(R.id.kz5);
datePicker = view.findViewById(R.id.date_picker);
}
xml code:
<DatePicker
android:id="@+id/date_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:layout_marginBottom="40dp"
android:layout_alignParentBottom="true"
android:calendarViewShown="false"/>
Upvotes: 0
Views: 214
Reputation: 1520
Try with the below code without xml required, it will help you.
public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(this, this, 2021, 1, 1);
datePickerDialog.show();
}
});
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Log.d("selectedDate",""+year+"-"+month+"-"+dayOfMonth);
}
}
Upvotes: 1
Reputation: 3252
First, in your layout set edittext as android:enabled="false"
or do it programmatically as edtDate.setEnabled(false);
And set click event to open date picker.
edtDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
edtDate.setText(String.format("%02d", dayOfMonth) + "-" + String.format("%02d", (monthOfYear + 1)) + "-" + String.format("%02d", year));
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Upvotes: 1
Reputation: 1675
You can add a listener to listen the change on DatePicker, like this:
datePicker.init(2021, 1, 1, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// use year month day here
}
});
Upvotes: 1