Android datepicker change color

Как изменить стиль DatePicker в android?

Я хочу изменить цвет по умолчанию диалога выбора даты/времени в Android, чтобы он соответствовал теме моего приложения. Я искал решение в Google, но я не мог найти решение.

то, что я делал, создавало новый стиль:

Не знаю, какие атрибуты доступны для диалога выбора даты. Было бы здорово, если бы кто-нибудь мог опубликовать ссылку на это

и после добавления стиля я называл его в моем основной стиль как

к сожалению, это не работает для меня вообще.

5 ответов

следуйте этому, это даст вам все типы выбора даты стиль (копировать из этого)

попробуйте это. Это самый простой и эффективный способ

чтобы изменить цвета DatePicker (режим календаря) на уровне приложения, определите ниже свойства.

(Я использую React Native; targetSdkVersion 22). Я пытаюсь изменить внешний вид диалога выбора даты календаря. Принятый ответ не работа для меня, но это сделал. Надеюсь, этот фрагмент поможет некоторым из вас.

Источник

Создаем красивый Date/Time/Data Picker в Android

Рано или поздно любой разработчик сталкивается с мыслью, что что-то в жизни нужно написать так, чтобы нравилось не заказчику, а самому себе. Решив, что наконец-то я созрел для написания приложения для Android, которым я сам бы пользовался с удовольствием — столкнулся с тем, что внешний вид вьюх в Android не очень-то и готов к воплощению моих красивых идей. И если обычные кнопки и TextView легко поддаются переделке, то вот с TimePicker-ом дела обстоят намного хуже. Творческая часть мозга взбунтовалась и решила, что если в приложении и будет Date/TimePicker, то такой, чтобы им было не только удобно, но и приятно пользоваться, иначе она (та самая творческая часть мозга) объявит бойкот и перестанет помогать.

Ну что же, вызов принят, напишем свой Picker с преферансом и куртизанками.


Именно такой Picker мы будем сооружать.

(Для тех кто просто хочет использовать виджет — ссылка на Git в конце статьи)

Первым делом пришлось ответить себе вопросы — а каким должен быть этот самый Picker и что он должен уметь делать?

Конечно, на вкус и цвет фломастеры разные, но если сравнить стилистику конкурирующих Picker-ов, то на мой взгляд выигрывает правый:


Time picker в Android(слева) и iOS (справа)

Пришлось отвечать для себя — а чем же привлекательнее правый Picker?

Ответ был не один:

  • Приятнее выглядит
  • Интуитивное переключение
  • Никаких лишних элементов

Но настроение хотело большего и поэтому сразу же были добавлены пункты, которые должны присутствовать в новом Picker’e.

  • Возможность легко менять размер без ущерба дизайну
  • Возможность указывать не только время но и… да вообще любую информацию
  • Все-таки должно быть более андроидным нежели яблочным

Итак, цели обозначены, приступим.

Палитра

Вообще все цвета палитры подбирались вручную перед каждым добавлением элемента. Цвета сравнивались и корректировались. В итоге получилась следующая палитра:

Названия цветов думаю сами за себя говорят, но в любом случае в коде будут пояснения, так что разобраться не составит труда.

Вставляем данный код в наш color.xml.

Создание Picker’а

Picker относится к View Элементам, значит создаем класс DataPicker:

Нам понадобятся следующие переменные:

В конструкторы возможны передачи параметров, стилей и т.д. Нам все эти излишки в рамках данной статьи не понадобятся.

Затем нам необходимо переопределить метод onSizeChanged:

Это нужно для того, чтобы при каждом изменении размера нашего холста все наши элементы прорисовывались правильно. Всегда зная размеры холста мы точно сможем заполнить все его области.

Следующим этапом необходимо определиться с возможностями нашего Picker’a. Первым делом он должен получать значения, которые необходимо отображать. Создадим для этого метод:

Для данного метода мне понадобился Handler. Дело в том, что размеры холста в момент создания равны 0 как по ширине, так и по высоте. В данном методе мы обращаемся к классу данных, в котором лежат наши значения и их параметры. Но на всякий случай проверяем, задан ли нашему холсту какой-нибудь размер. И если размер еще не определен, то просто немного отложим выполнение данной функции.

Класс со значениями и их параметрами выглядит так:

Следующая возможность, которая должна быть — это возможность изменения значения Picker’a путем скролла.

Переопределим для этого метод OnTouch:

Собственно метод выравнивания наших значений после остановки скроллинга:

Как мы видим, в прошлом методе мы использовали функцию onSelected, чтобы наш Picker сообщил о том, что пользователь выбрал какое-то значение.

Создадим для этого слушатель и определим события:

Читайте также:  Музыкальный секвенсор для андроид

Когда все основные методы у нас определены, приступим к самому главному. Нам нужно отрисовать наш Picker на холсте. За отрисовку у нас отвечает метод onDraw:

Выглядеть это должно вот так:

С тенями уже получше:

Уже что-то интересное:

Так намного лучше:

Завершаем метод onDraw отловом ошибок и устанавливаем fps отрисовки:

Готово!

Удобство нашего Picker’a заключается в том, что мы можем их комбинировать для более удобного выбора значений.
Например, можно скомбинировать 4 компонента для выбора времени напоминания:

Дальше нашему Picker’у можно добавить обработку атрибутов, кастомные параметры, работу с адаптерами… Тут уже поле деятельности неисчерпаемо и в одной статье не разгуляться. Но если сообществу будет интересно продолжение — буду рад продолжить.

Источник

Android Datepicker – Using Datepickerdialog With Button

Hi and welcome to another tutorial from Codingdemos, in this tutorial you will learn how to use Android Datepicker to select a date from Android Datepickerdialog and show it inside Android TextView.

By the end of this tutorial, you will have an app that looks like this. (Large preview)

In this tutorial we will be using the following:

    – Android studio version 3.0.1
    – Android emulator Nexus 5X with API 26
    – Minimum SDK API 16

1- Open up Android Studio and create a new project and give it a name, in our case we’ve named it (DatePicker), choose API 16 as the minimum SDK, then choose a blank activity, click “Finish” and wait for Android Studio to build your project.

Create new Android Studio project. (Large preview)

2- Open up colors.xml file, add the following code to change the colors of the app.

3- Build and run the app to see the changes.

New colors for Android datepicker app. (Large preview)

4- Open up activity_main.xml file, here you want to add an Android Button and TextView.

  • btnDate: This is an Android Button that is placed in the center of the screen, it has a background color and a text color, it has some padding that surround the button and a text label that says (Select a date).
  • tvSelectedDate: This is an Android TextView that is placed below btnDate in the center of the screen, it has a margin from the top so that this TextView won’t be closed to the Button, it has a text color with some style and a text size of 30.

5- Now build and run the app to see the result.

Android Button for Date picker. (Large preview)

6- Next open up MainActivity.java file, here you need to define Android Button, TextView and DatePickerDialog.

7- You need to make selectDate Button clickable, so define Android SetOnClickListener.

8- Inside Android OnClick method is where you will define Android datepicker.

9- One thing left before you can see Android DatePickerDialog is to call the following method.

10- Now you can build and run the app to see the progress.

Android datepicker wrong date. (Large preview)

How to fix Android datepicker wrong date

In this section, you will learn how you can fix the issue about Android Date Picker showing the wrong date.

11- Open up MainActivity.java file, inside the Button OnClick method add the following code.

Here you need to define Android Calendar, using this Calendar you will be able to get current year, month and day values.

12- Now you need to change Android DatePickerDialog to be able to use the current date values.

13- Build and run the app to see the output.

Android datepicker current date. (Large preview)

14- Now you need to work on getting the selected date appears inside Android TextView, add the following code inside DatePickerDialog onDateSet method.

Here you want to show the date values separated by (/) inside Android TextView.

15- Now build and run the app.

Android datepicker wrong month. (Large preview)

How to fix Android Date Picker wrong month issue

In this section, you will learn how you can fix issue that is causing Android Date Picker to show the wrong month.

16- The reason why it’s giving you the wrong month, because in Android Date API the month index value is (0-11). So if you choose the month February you will get the month value as January, if you choose the month December you will get the month value as November.

17- Add the following code inside Android DatePickerDialog onDateSet method.

18- Now build and run the app to see the result.

Android datepicker showing correct month. (Large preview)

How to disable past dates in Android datepicker

19- It feels great to see datepicker dialog working 🙂 Now you might be thinking on how you can prevent the user from choosing past dates! Well all you have to do is add the following code before calling datePickerDialog.show();.

DatePickerDialog has a method called setMinDate which you need to pass the current time by calling System.currentTimeMillis(). This will disable previous dates based on the current time.

Читайте также:  Рпг офлайн для андроида

20- Build and run the app to see it in action.

Android datepicker past dates. (Large preview)

21- Here is the full code for MainActivity.java file.

20- The source code for Android Date Picker example is available on GitHub, I hope you find this tutorial helpful and if you have any question please post them in the comment below.

Источник

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.

Источник

Читайте также:  Сколько весит установленный андроид 10
Оцените статью