Changing the date in an EditText field on Android Studio

Can someone assist me in updating an EditText with the selected date from a DatePicker as it changes? Here 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);
    }

This is the XML code for the DatePicker:

<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"/>

Answer №1

To monitor any changes made to the DatePicker, you can set up a listener as shown below:

    datePicker.init(2021, 1, 1, new DatePicker.OnDateChangedListener() {
        @Override
        public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            // Perform actions based on the selected year, month, and day
        }
    });

Answer №2

To start with, in your design make sure to set the edittext as

android:enabled="false"
, or you can achieve this programmatically using edtDate.setEnabled(false);

Next, add a click event to trigger the opening of the 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();
    }
}
});

Answer №3

Utilize the following code snippet to achieve your goal without the need for XML, it's a simple and effective approach.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to showcase specific row information in a vuetify data table on Vue.js by implementing icon clicks

I am currently working on a Vuetify data table that showcases order information, with an option for users to cancel their orders by clicking on the cancel icon. Upon clicking the cancel icon, a confirmation overlay pops up displaying the specific order id. ...

You are limited to storing only up to 2 items in the localStorage

My goal is to save items in local storage as an array of objects. Initially, it works perfectly and stores the first element in local storage as needed. However, I am facing an issue where I cannot store more than one element. Below is the code block that ...

Utilizing System.import with Webpack 2 and React for splitting code and managing nested routes

I followed the instructions from a tutorial article on Modus Create titled Code Splitting for React Router with ES6 Imports to create an app. I made some modifications by adding children routes, resulting in the following router configuration: function er ...

Problem with loading messages in VueI18n locale

Utilizing the vueI18n package for language localization in our application, we fetch the locale messages object via an api call. Within our config file, we have specified the default language which is used to load the locale before the creation of app.vue. ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...

Arranging xCharts based on the weekday order

Struggling with xCharts, specifically trying to display a bar chart showing numbers with corresponding days of the week in order. Despite my efforts, I can't seem to get them to appear in the correct sequence. Refer to the image below for reference: ...

Experiencing an unusual issue with grunt: The Gruntfile.js seems to be missing the 'flatten' method

Encountering an unusual error message while attempting to run grunt stated: TypeError: Object Gruntfile.js has no method 'flatten' Being a beginner with node.js, npm, and grunt, I believe my installation of node, npm, and grunt was done correctl ...

Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts getListOfNames() { return this.http.get(this.BaseURL + 'welcome/getnama') .pipe(map(response => { return response; })); } After making the API call, I receive the following resp ...

Guide to quickly redirecting all 404 links to the homepage on a simple HTML website

Is there a way to automatically redirect clients to the homepage if they click on a broken link in a basic HTML website, instead of displaying a custom 404 page? UPDATE: My website consists of only 5 plain HTML pages hosted on GoDaddy. There is no server- ...

Vue component encounters undefined error when passing prop array through component

My challenge is passing an array of dates to my component, but I keep encountering this error: [Vue warn]: Property or method "dates" is not defined on the instance but referenced during render I'm puzzled by this issue because I am receiving the ...

What is the best way to load distinct scripts based on the state in nextjs?

My current challenge involves loading different scripts for English and Hebrew languages within the state. Despite changing the redux useSelector value to Hebrew, the Hebrew script is not being rendered, and the English button always appears on the right s ...

Tips for Managing Errors During Zip File Extraction in Node.js

Currently, my task involves uploading a zip file, extracting it on the server side, and handling any errors that may occur during the extraction process. I am attempting to achieve this using the following code: var zip = new AdmZip(x); zip.extractAllTo( ...

Using the video-js feature to play multiple videos simultaneously

Is it possible to play multiple videos using video-js functionality simultaneously? The answer is yes! Check out Fiddle 1 However, an issue arises when wrapping a trigger, such as a button, around the function that invokes playVideo(). This causes the v ...

Ways to detect the use of vue.js on a webpage without relying on vue-devtools

One way to determine if the page is utilizing Angular or AngularJS is by inspecting window.ng and window.angular. Is there a similar method to identify whether Vue is being used on the page directly from the console, without relying on vue-devtools? ...

Using more than one button to activate a single Material-UI Popper component

I recently found myself in a situation where I needed to activate the Material-UI <Popper /> component from various clickable elements. According to the Popper component API on the official Material-UI website, setting the anchorEl property determine ...

I am trying to understand why my React component's render function is being called twice - first without any data and then again with data, resulting in a

I am facing an issue with my TreeNav component, where the data is fetched from an API call. I have set up the reducer, action, and promise correctly, but when I try to map over the data in the component render function, I get an error saying "Uncaught Type ...

Implementing conditional validation in Formik on cancel button click in a React application

When defocusing from the field without entering any data, a validation error occurs. Similarly, if you click on the submit button without giving a value, a validation error is triggered - this behavior is expected. However, how can we prevent the validat ...

Color section of a highcharts graph

Is there a way to paint the final section of a highcharts chart similar to what is shown in this image? Chart If painting the last section is not possible, would changing the color of those final datapoints be a feasible alternative? Thank you! ...

What are the steps to crafting a basic JavaScript or jQuery function within CodeIgniter?

I'm currently working on creating a basic JavaScript function within CodeIgniter that is triggered when a radio button is clicked. <input type="radio" name="amount" value="<?php echo $plan['amount']; ?>" onclick="fn()" /> The J ...

How can the 'selected' attribute be assigned to 'select/option' tags depending on the option value?

In my code, I have a select input with various options and values. I want to set the 'selected' attribute for the option that corresponds to a specific value X. Here is an example: // If x=3, I want the option with value=3 to be marked as 's ...