1. 程式人生 > >Android中日曆控制元件的使用

Android中日曆控制元件的使用

一.概述

因為專案中要用到選擇日期的功能,所以特此來研究一下相關方面的知識,總結一下,也為了以後使用起來更加方便。

二.介紹

Android中自帶了兩個控制元件,DatePicker和TimePicker,分別用來選擇日期和時間的,我們看看如何使用。

使用一

佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.example.calendardemo.MainActivity">
<DatePicker android:id="@+id/datepicker" android:layout_width="wrap_content" android:calendarViewShown
="true" android:layout_height="wrap_content"/>
<TimePicker android:id="@+id/timepicker" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>

這裡有句程式碼控制是否顯示日曆檢視

 android:calendarViewShown="true"

程式碼

public class MainActivity
extends AppCompatActivity {
private DatePicker datePicker; private TimePicker timePicker; private int year; private int month; private int day; private int hour; private int minute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); datePicker = (DatePicker) findViewById(R.id.datepicker); timePicker = (TimePicker) findViewById(R.id.timepicker); timePicker.setIs24HourView(true); initData(); } public void initData(){ Calendar calendar = Calendar.getInstance(); year = calendar.get(Calendar.YEAR); month = calendar.get(Calendar.MONTH); day = calendar.get(Calendar.DAY_OF_MONTH); hour = calendar.get(Calendar.HOUR_OF_DAY); minute = calendar.get(Calendar.MINUTE); datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Toast.makeText(MainActivity.this, year+"年"+monthOfYear+"月"+dayOfMonth+"日", Toast.LENGTH_SHORT).show(); } }); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { Toast.makeText(MainActivity.this, hourOfDay+"時"+minute+"分", Toast.LENGTH_SHORT).show(); } }); } }

效果圖
這裡寫圖片描述
我們將程式碼改成如下

 android:calendarViewShown="false"

效果圖
這裡寫圖片描述

可以看到日曆控制元件已經沒有了。

使用二

有時候我們需要將兩個控制元件顯示到一起,也就是水平排列,這時候怎麼做呢,是不是修改佈局檔案就可以了呢?我們試試,我們把最外層的線性佈局方向改為水平方向
這裡寫圖片描述

我們看到時間控制元件顯示不全了,接下來我們再將兩個控制元件的weight都設定為1,讓它們平分水平方向距離

這裡寫圖片描述

這時候日期控制元件又顯示不全了。

通過上面兩種方式,說明我們如果將兩個控制元件顯示到一起的話會出現問題,下面我們來看看解決方案。

使用三

接下來我們要解決的就是如何讓這兩個控制元件顯示在一起,並且都完整顯示。
我們先看效果圖
這裡寫圖片描述

我們可以看到兩個控制元件已經全部顯示在了對話方塊中,下面直接給出實現程式碼

public class ChooseDateDialog  {
    private static DatePicker datePicker;
    private static TimePicker timePicker;
    private int mYear;
    private int mMonth;
    private int mDay;
    private int mHour;
    private int mMinute;
    public  void showDialog(Context context, final EditText editText) {
        View view = View.inflate(context, R.layout.dialog_date_time_layout, null);
        datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        timePicker = (TimePicker) view.findViewById(R.id.time_picker);
        timePicker.setIs24HourView(true);
        resizePikcer(datePicker);
        resizePikcer(timePicker);
        initData();
        new AlertDialog.Builder(context).setTitle("請選擇日期").setView(view).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("確定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                GregorianCalendar gregorianCalendar = new GregorianCalendar(mYear,mMonth,mDay,mHour,mMinute);
                String result = format.format(gregorianCalendar.getTime());
                editText.setText(result);
                dialog.dismiss();
            }
        }).create().show();
    };
    public void initData(){
        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
        mHour = calendar.get(Calendar.HOUR_OF_DAY);
        mMinute = calendar.get(Calendar.MINUTE);
        datePicker.init(mYear, mMonth, mDay, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
            }
        });
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
            }
        });
    }
    private void resizePikcer(FrameLayout tp){
        List<NumberPicker> npList = findNumberPicker(tp);
        for(NumberPicker np:npList){
            resizeNumberPicker(np);
        }
    }

    /**
     * 得到viewGroup裡面的numberpicker元件
     * @param viewGroup
     * @return
     */
    private List<NumberPicker> findNumberPicker(ViewGroup viewGroup){
        List<NumberPicker> npList = new ArrayList<NumberPicker>();
        View child = null;
        if(null != viewGroup){
            for(int i = 0; i < viewGroup.getChildCount(); i++){
                child = viewGroup.getChildAt(i);
                if(child instanceof NumberPicker){
                    npList.add((NumberPicker)child);
                }
                else if(child instanceof LinearLayout){
                    List<NumberPicker> result = findNumberPicker((ViewGroup)child);
                    if(result.size()>0){
                        return result;
                    }
                }
            }
        }
        return npList;
    }
    /*
     * 調整numberpicker大小
     */
    private void resizeNumberPicker(NumberPicker np){
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        np.setLayoutParams(params);
    }
}