Android datepicker from to

DatePicker

Элемент DatePicker позволяет пользователю выбрать дату (число, месяц, год). Данный виджет используют как правило на отдельном экране. Также существует похожее по функционалу диалоговое окно DatePickerDialog.

DatePicker находился в разделе Date & Time в Android Studio 3.01. Сейчас на панели инструментов данного компонента нет, поэтому придётся добавлять вручную.

Нужно помнить, что внутренняя нумерация месяцев в Android начинается с 0, поэтому январь = 0, февраль = 1 и т.д. Поэтому как правило, в коде следует прибавлять единицу к значению месяца при работе с датой или наоборот — отнимать единицу, если данные поступают снаружи (например, из текстового поля).

Добавим на экран текстовую метку, кнопку и виджет даты:

Пользователь может выбрать любую дату на виджете, а обычный щелчок на кнопке позволит отобразить выбранную дату в текстовой метке. Длительное нажатие на кнопку устанавливает текущую дату на виджете и в текстовой метке.

Настройка даты на самом виджете происходит через метод init(). Изменение даты можно прослушивать через OnDateChangedListener():

Настройка компонента

По умолчанию DatePicker состоит из двух элементов — Spinner и CalendarView. Вы можете настроить внешний вид компонента, если укажете через XML-атрибуты android:calendarViewShown и android:spinnersShown, какой элемент не нужно выводить. Также можно это сделать программно через методы setCalendarViewShown() и setSpinnersShown() (API level 11).

Напишем пример программного управления внешним видом DatePicker:

Код для активности:

Новый внешний вид в Android 5.0 (API 21) Lollipop

В Android 5.0 (API 21) внешний вид компонента изменился. Поэтому неплохо бы проверить, всё ли работает в старом коде.

Скриншот взят из статьи Криминальное чтиво.

Источник

Android datepicker from to

Android DatePicker Example

October 04, 2017

Android DatePicker allows user to select a date making the picked date valid and formatted correctly. DatePicker can be used in two modes: calendar mode and spinner mode. If you use material themes, by default DatePicker is displayed as calendar view.

In this post, you can find details on DatePickerDialog, DatePicker widget, DatePicker material styles, DatePicker custom material styles, DatePicker event handling, DatePicker calendar, DatePicker spinner, and DatePicker spinner styles.

Android DatePickerDialog Example

Date picker can be shown as dialog using DatePickerDialog. To use DatePickerDialog, first you need to create a dialog fragment by extending DialogFragment and implementing onCreateDialog method which returns DatePickerDialog instance. In the implementation of onCreateDialog method of date picker fragment, instantiate DatePickerDialog by setting current date and return it.

Below DatePickerDialog examples displays a screen with button, on clicking it, date picker dialog will be shown and the picked date will be displayed as a toast message.

DatePicker fragment

Activity

Activity layout

Android DatePickerDialog example output

Android DatePickerDialog event handling

As shown in the above date picker example, date picker event can be handled by implementing DatePickerDialog.OnDateSetListener. DatePickerDialog.OnDateSetListener has a callback method onDateSet which gets called when date is picked from date picker dialog. In onDateSet method, you can get user selected date as shown in the code below.

Above date set callback method gets called every time date is picked only after adding it to DatePickerDialog by passing it to constructor of the DatePickerDialog.

Читайте также:  Discover pro mib 1 android auto

DatePicker Widget Example

DatePicker can be shown using DatePicker widget. To use DatePicker widget first define date picker in layout xml as shown below.

Layout with DatePicker widget

Activity

DatePicker widget date change listener

To handle DatePicker widget events, you need to implement DatePicker.OnDateChangedListener and add it to DatePicker widget by calling setOnDateChangedListener method. DatePicker.OnDateChangedListener has one callback onDateChanged which gets called when date is changed and this where you can get user picket date, see above code for details.

DatePicker widget output

Android DatePicker Material Style

DatePicker material styles application level

Android platform provides material styles for DatePicker following material design guidelines. Above pictures show default material style of DatePicker with application them set to app compact material style Theme.AppCompat.Light.DarkActionBar.

Date picker style can be customized at application level by extending app compact themes and setting color properties as shown below.

DatePicker output using custom theme.

DatePicker material styles individual

With the above custom theme, all UI controls throughout the application get impacted. To customize only DatePicker in your application, you need to extend android material themes for DatePicker widget (Widget.Material.DatePicker) or alert dialog (ThemeOverlay.AppCompat.Dialog.Alert) and set datePickerStyle or datePickerDialogTheme properties of app compact application theme.

Below style is a custom DatePickerDialog theme.

Below style extends app compact theme with datePickerDialogTheme set to above custom theme.

Below picture shows date picker output after applying above custom theme to application.

Android DatePicker Spinner

If you use material themes, by default the data picker is in calendar mode. You can change the look of DatePicker by setting datePickerMode attribute to either spinner or calendar mode.

Below style sets datepicker mode to spinner.

Apply above style to date picker.

Ouput of date picker in spinner mode.

If datePickerMode is set spinner and calendarViewShown is not set to false, both spinner and calendar views will be displayed as shown below.

Android DatePicker Spinner Style

Below custom material style for spinner DatePicker sets selection divider color.

About

Android app development tutorials and web app development tutorials with programming examples and code samples.

Источник

Android DatePicker with Examples

In android, DatePicker is a control that will allow users to select the date by a day, month and year in our application user interface.

If we use DatePicker in our application, it will ensure that the users will select a valid date.

Following is the pictorial representation of using a datepicker control in android applications.

Generally, in android DatePicker available in two modes, one is to show the complete calendar and another one is to show the dates in spinner view.

Create Android DatePicker in XML Layout File

In android, we can create a DatePicker in XML layout file using element with different attributes like as shown below

DatePicker android :id= «@+id/datePicker1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»/>

In anroid, the DatePicker supports a two types of modes, those are Calendar and Spinner to show the date details in our application.

Android DatePicker with Calendar Mode

We can define android DatePicker to show only a calendar view by using DatePicker android :datePickerMode attribute.

Following is the example of showing the DatePicker in Calendar mode.

DatePicker
android :id= «@+id/datePicker1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :datePickerMode= «calendar»/>

The above code snippet will return the DatePicker in android like as shown below

If you observe the above result we got the DatePicker in calendar mode to select a date based on our requirements.

Android DatePicker with Spinner Mode

If we want to show the DatePicker in spinner format like showing day, month and year separately to select the date, then by using DatePicker android :datePickerMode attribute we can achieve this.

Following is the example of showing the DatePicker in Spinner mode.

Читайте также:  Что будет после перепрошивки андроида

The above code snippet will return the DatePicker in android like as shown below

If you observe the above result we got the DatePicker in both Spinner and Calendar modes to select the date.

To get only spinner mode date selection, then we need to set android :calendarViewShown= «false» attribute in DatePicker control like as shown below.

DatePicker
android :id= «@+id/datePicker1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :datePickerMode= «spinner»
android :calendarViewShown= «false»/>

The above code will return the DatePicker like as shown below

If you observe the above result we got the DatePicker in spinner mode to select the date separately by day, month and year.

This is how we can use DatePicker in different modes based on our requirements in android applications.

Android DatePicker Control Attributes

The following are some of the commonly used attributes related to DatePicker control in android applications.

Attribute Description
android:id It is used to uniquely identify the control
android:datePickerMode It is used to specify datepicker mode either spinner or calendar
android:background It is used to set the background color for the date picker.
android:padding It is used to set the padding for left, right, top or bottom of the date picker.

Android DatePicker Example

Following is the example of defining one DatePicker control, one TextView control and one Button control in RelativeLayout to show the selected date on Button click in the android application.

Create a new android application using android studio and give names as DatePickerExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
RelativeLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent» android :layout_height= «match_parent» >
DatePicker
android :id= «@+id/datePicker1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_centerHorizontal= «true»
android :layout_marginTop= «20dp»/>
Button
android :id= «@+id/button1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/datePicker1»
android :layout_marginLeft= «100dp»
android :text= «Get Date»/>
TextView
android :id= «@+id/textView1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/button1»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «10dp»
android :textStyle= «bold»
android :textSize= «18dp»/>
RelativeLayout >

If you observe above code we created a one DatePicker control, one TextView control and one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.datepickerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.datepickerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity <
DatePicker picker ;
Button btnGet ;
TextView tvw ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
tvw =(TextView)findViewById(R.id. textView1 );
picker =(DatePicker)findViewById(R.id. datePicker1 );
btnGet =(Button)findViewById(R.id. button1 );
btnGet .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
tvw .setText( «Selected Date: » + picker .getDayOfMonth()+ «/» + ( picker .getMonth() + 1 )+ «/» + picker .getYear());
>
>);
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are trying to show the selected date of DatePicker on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android DatePicker Example

When we run the above example using an android virtual device (AVD) we will get a result like as shown below.

If you observe the above result, we are getting the date from DatePicker when we click on Button in the android application.

Now we will see another example of showing the DatePicker control on EditText click event and get the selected date value in the android application.

Android Show DatePicker on EditText Click Example

Following is the example of open or popup datepicker dialog when we click on EditText control and get the selected date value on Button click in the android application.

Create a new android application using android studio and give names as DatePickerExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

xml version= «1.0» encoding= «utf-8» ?>
RelativeLayout xmlns: android = «http://schemas.android.com/apk/res/android»
android :layout_width= «match_parent» android :layout_height= «match_parent» >
EditText
android :id= «@+id/editText1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «150dp»
android :ems= «10»
android :hint= «Enter Date»/>
Button
android :id= «@+id/button1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/editText1»
android :layout_marginLeft= «100dp»
android :text= «Get Date»/>
TextView
android :id= «@+id/textView1»
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :layout_below= «@+id/button1»
android :layout_marginLeft= «100dp»
android :layout_marginTop= «10dp»
android :textStyle= «bold»
android :textSize= «18dp»/>
RelativeLayout >

If you observe above code we created a one EditText control, one TextView control and one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout resource from our activity onCreate() callback method, for that open main activity file MainActivity.java from \java\com.tutlane.datepickerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.datepickerexample;
import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity <
DatePickerDialog picker ;
EditText eText ;
Button btnGet ;
TextView tvw ;
@Override
protected void onCreate(Bundle savedInstanceState) <
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
tvw =(TextView)findViewById(R.id. textView1 );
eText =(EditText) findViewById(R.id. editText1 );
eText .setInputType(InputType. TYPE_NULL );
eText .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar. DAY_OF_MONTH );
int month = cldr.get(Calendar. MONTH );
int year = cldr.get(Calendar. YEAR );
// date picker dialog
picker = new DatePickerDialog(MainActivity. this ,
new DatePickerDialog.OnDateSetListener() <
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) <
eText .setText(dayOfMonth + «/» + (monthOfYear + 1 ) + «/» + year);
>
>, year, month, day);
picker .show();
>
>);
btnGet =(Button)findViewById(R.id. button1 );
btnGet .setOnClickListener( new View.OnClickListener() <
@Override
public void onClick(View v) <
tvw .setText( «Selected Date: » + eText .getText());
>
>);
>
>

If you observe above code we are calling our layout using setContentView method in the form of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file name activity_main and we are trying to show the DatePicker on EditText click, get the selected date of EditText control on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.

Output of Android Show DatePicker on EditText Click Example

When we run the above example using an android virtual device (AVD) we will get a result like as shown below.

If you observe the above result, we are able to open the DatePicker on EditText click and showing the selected date value in EditText control and getting EditText control value on Button click in the android application.

This is how we can use DatePicker control in android applications to pick the date based on our requirements.

Источник

Читайте также:  Всплывает яндекс для андроид
Оцените статью