Android日历视图

In this tutorial, we’ll be discussing the Calendar Widget using the CalendarView class in our Android Application.

在本教程中,我们将使用Android应用程序中的CalendarView类讨论Calendar Widget。

Android日历视图 (Android Calendar View)

As the name suggests, a Calendar View is used to display and select dates of the Calendar.

顾名思义,“日历视图”用于显示和选择日历的日期。

To add a CalendarView in the XML Layout do the following:

要在XML布局中添加CalendarView,请执行以下操作:

<CalendarView
        android:id="@+id/calendarView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

This is how it looks in the Layout Design editor :

这是在“布局设计”编辑器中的外观:

When you’ll run the above application on your device, it’ll show the current date. By default, the Calendar shows the Jan 1, 1970, date.

当您在设备上运行上述应用程序时,它将显示当前日期。 默认情况下,日历显示1970年1月1日的日期。

android:maxDate and android:minDate are used to set a custom range on the calendar. The dates specified are of the format MM/dd/yyyy.

android:maxDateandroid:minDate用于在日历上设置自定义范围。 指定的日期格式为MM / dd / yyyy。

To do the same in Java we use setMaxDate() and setMinDate() methods passing the long instance. The getters methods are available for the same.

为了在Java中执行相同的操作,我们使用setMaxDate()setMinDate()方法传递long实例。 吸气方法同样适用。

To set the current date we do setDate(long date) on the CalendarView instance.

要设置当前日期,我们在CalendarView实例上执行setDate(long date)

The setDate method has another form: setDate(long date, boolean animate, boolean center).
By default the second and third parameters are true. When you select a new date it animates to it.

setDate方法具有另一种形式: setDate(long date, boolean animate, boolean center)
默认情况下,第二个和第三个参数为true。 当您选择一个新的日期时,它会动画化。

To change the date and week text style we use the attributes:
android:dateTextAppearance and android:weekTextAppearance or their equivalent setters in Java.

要更改日期和星期文本样式,我们使用以下属性:
android:dateTextAppearanceandroid:weekTextAppearance或它们在Java中的等效设置器。

The CalendarView consists of the following listener:

CalendarView由以下侦听器组成:

calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView calendarView, int i, int i1, int i2) {
            }
        });

This gets triggered whenever the date is changed by the user.

每当用户更改日期时,都会触发此事件。

  • i = year

    我=年
  • i1 = month

    i1 =月
  • i2 = day

    i2 =天

In the following section, we’ll create an android application with a custom theme and add a custom range on the CalendarView along with showing the difference between animation and non-animation date changes.

在下一节中,我们将创建一个具有自定义主题的android应用程序,并在CalendarView上添加自定义范围,并显示动画和非动画日期更改之间的差异。

项目结构 (Project Structure)

(Code)

In the styles.xml file add the following three styles:

在styles.xml文件中,添加以下三种样式:

<style name="CalenderViewCustom" parent="Theme.AppCompat">
        <item name="colorAccent">@android:color/holo_blue_dark</item>
        <item name="colorPrimary">@android:color/darker_gray</item>
        <item name="android:textColorPrimary">@color/colorPrimary</item>
    </style>

    <style name="CalenderViewDateCustomText" parent="android:TextAppearance.DeviceDefault.Small">
        <item name="android:textColor">@android:color/holo_orange_dark</item>
    </style>

    <style name="CalenderViewWeekCustomText" parent="android:TextAppearance.DeviceDefault.Small">
        <item name="android:textColor">@android:color/holo_green_dark</item>
    </style>

android:textColorPrimary by default is white. This color is set on the month date and the left and right indicators.

android:textColorPrimary默认为白色。 该颜色设置在月份日期以及左右指示符上。

The code for the activity_main.xml is given below:

下面给出了activity_main.xml的代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <CalendarView
        android:id="@+id/calendarView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:dateTextAppearance="@style/CalenderViewDateCustomText"
        android:theme="@style/CalenderViewCustom"
        android:weekDayTextAppearance="@style/CalenderViewWeekCustomText"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnWithAnim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:text="With\nAnim"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/btnWithoutAnim"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/btnRange" />

    <Button
        android:id="@+id/btnWithoutAnim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Without\nAnim"
        app:layout_constraintBaseline_toBaselineOf="@+id/btnWithAnim"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/btnWithAnim" />

    <Button
        android:id="@+id/btnRange"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom\nRange"
        app:layout_constraintEnd_toStartOf="@+id/btnWithAnim"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/btnWithAnim" />


</android.support.constraint.ConstraintLayout>

We’ve added all the custom styles in the layout above.

我们在上面的布局中添加了所有自定义样式。

The three Buttons are chained in the Constraint Layout.

这三个按钮链接在“ 约束布局”中

The code for the MainActivity.java is given below:

MainActivity.java的代码如下:

package com.journaldev.androidcalendarview;

import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Calendar calendar;
    CalendarView calendarView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        calendar = Calendar.getInstance();


        calendar.set(Calendar.MONTH, Calendar.NOVEMBER);
        calendar.set(Calendar.DAY_OF_MONTH, 9);
        calendar.set(Calendar.YEAR, 2012);


        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.add(Calendar.YEAR, 1);


        calendarView = findViewById(R.id.calendarView);

        Button btnRange = findViewById(R.id.btnRange);
        btnRange.setOnClickListener(this);

        Button btnWithoutAnim = findViewById(R.id.btnWithoutAnim);
        btnWithoutAnim.setOnClickListener(this);

        Button btnWithAnim = findViewById(R.id.btnWithAnim);
        btnWithAnim.setOnClickListener(this);

        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView calendarView, int i, int i1, int i2) {

                String msg = "Selected date Day: " + i2 + " Month : " + (i1 + 1) + " Year " + i;
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();


            }
        });

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btnWithAnim:
                calendarView.setDate(calendar.getTimeInMillis(), true, true);
                break;

            case R.id.btnWithoutAnim:
                calendar.set(Calendar.DAY_OF_MONTH, 12);
                calendar.set(Calendar.YEAR, 2016);
                calendar.add(Calendar.MONTH, Calendar.MARCH);
                calendarView.setDate(calendar.getTimeInMillis(), false, false);
                break;

            case R.id.btnRange:

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
                long endOfMonth = calendar.getTimeInMillis();
                calendar = Calendar.getInstance();
                calendar.set(Calendar.DATE, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                long startOfMonth = calendar.getTimeInMillis();
                calendarView.setMaxDate(endOfMonth);
                calendarView.setMinDate(startOfMonth);


                String minDateString = new SimpleDateFormat("MM/dd/yyyy").format(new Date(calendarView.getMinDate()));
                String maxDateString = new SimpleDateFormat("MM/dd/yyyy").format(new Date(calendarView.getMaxDate()));

                Toast.makeText(getApplicationContext(), "MMDDYYYY Min date - " + minDateString + " Max Date is " + maxDateString, Toast.LENGTH_LONG).show();

                break;


        }
    }
}

calendar.getActualMaximum(Calendar.DATE) gets the end of the month for the current date.
We’ve used SimpleDateFormat to convert the dates into a custom format.

calendar.getActualMaximum(Calendar.DATE)获取当前日期的月底。
我们使用SimpleDateFormat将日期转换为自定义格式。

The output of the application in action is given below:

实际应用程序的输出如下:

In the first case, we animate to another date with animation. In the last case, the custom range shows only the July Month. The indicators are disabled.

在第一种情况下,我们使用动画为另一个日期设置动画。 在最后一种情况下,自定义范围仅显示七月。 指示灯已禁用。

This brings an end to this tutorial. You can download the project from the link below:

本教程到此结束。 您可以从下面的链接下载项目:

翻译自: https://www.journaldev.com/22321/android-calendar-view

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值