1. 程式人生 > >android之時間選擇器

android之時間選擇器

剛做一個測試專案,有一個時間選擇器,後面雖然不打算用了,但還是要貼出來,畢竟花了一點時間



現在就直接上程式碼了,裡面會講的很詳細,自定義View的

DateSelect.java

public class DateSelect extends LinearLayout implements View.OnClickListener {
    private Context context;//上下文
    private LinearLayout layout;//兩個button佈局
    private TextView tvShowDate;//顯示日期
    private TextView tvShowWeek;//顯示星期
    private Button btnUp;//日期加1
    private Button btnDown;//日期減1
    private DatePickerDialog datePickerDialog;//彈出框日期控制元件

    public DateSelect(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        //載入佈局
        LayoutInflater.from(context).inflate(R.layout.view_date_select, this, true);

        //初始化
        layout = (LinearLayout) findViewById(R.id.date_select_ll_layout);
        tvShowDate = (TextView) findViewById(R.id.date_select_tv_show_date);
        tvShowWeek = (TextView) findViewById(R.id.date_select_tv_show_week);
        btnUp = (Button) findViewById(R.id.date_select_btn_up);
        btnDown = (Button) findViewById(R.id.date_select_btn_down);

        //獲取相關屬性
        TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.date_select);
        if (attributes != null) {
            //設定背景 , 注意R.styleable.date_select_bgColor 是用_拼接的
            int bgColorId = attributes.getResourceId(R.styleable.date_select_bg_color, Color.WHITE);
            this.setBackgroundColor(bgColorId);

            //獲取文字
            String textDate = attributes.getString(R.styleable.date_select_tv_show_date_text);
            String textWeek = attributes.getString(R.styleable.date_select_tv_show_week_text);
            //獲取字型顏色
            int textColor = attributes.getColor(R.styleable.date_select_tv_show_time_text_color, Color.BLACK);
            //獲取字型大小
            float textSize = attributes.getInt(R.styleable.date_select_tv_show_time_text_size, 18);
            if (!TextUtils.isEmpty(textDate)) {
                tvShowDate.setText(textDate);
                tvShowDate.setTextColor(textColor);
                tvShowDate.setTextSize(textSize);

                tvShowWeek.setText(textWeek);
                tvShowWeek.setTextColor(textColor);
                tvShowWeek.setTextSize(textSize);
            }

            //設定btnUp的背景
            int btnUpBgId = attributes.getResourceId(R.styleable.date_select_btn_up_bg, -1);
            if (btnUpBgId != -1) {
                btnUp.setBackgroundResource(btnUpBgId);
            }

            //設定btnDown的背景
            int btnDownBgId = attributes.getResourceId(R.styleable.date_select_btn_down_bg, -1);
            if (btnDownBgId != -1) {
                btnDown.setBackgroundResource(btnDownBgId);
            }

            //是否隱藏兩個Button,預設隱藏
            boolean isVisible = attributes.getBoolean(R.styleable.date_select_layout_visible, true);
            if (isVisible) {
                layout.setVisibility(View.GONE);
            } else {
                layout.setVisibility(View.VISIBLE);
            }

            //回收 TypedArray,用於後續呼叫時可複用之。當呼叫該方法後,不能再操作該變數。
            attributes.recycle();
        }

        setOnClickListener();
    }

    //新增事件
    private void setOnClickListener() {
        btnDown.setOnClickListener(this);
        btnUp.setOnClickListener(this);
        tvShowDate.setOnClickListener(this);
        tvShowWeek.setOnClickListener(this);
    }

    /**
     *  設定顯示日期
     *  @param dateStr 日期字串
     */
    public void setTvShowDate(String dateStr){
        if(!TextUtils.isEmpty(dateStr)){
            tvShowDate.setText(dateStr);
            tvShowWeek.setText(DateUtil.getWeekByDate(DateUtil.getDateByStr(dateStr)));
        }
    }

    /**
     *  獲取當前日期
     */

    public Date getTvShowDate(){
        return DateUtil.getDateByStr(tvShowDate.getText().toString());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //選擇日期
            case R.id.date_select_tv_show_date:
            case R.id.date_select_tv_show_week:
                datePickerDialog = new DatePickerDialog(this.context, AlertDialog.THEME_HOLO_DARK, new DatePickerDialog.OnDateSetListener() {
                    public void onDateSet(DatePicker datePicker, int mYear, int mMonth, int mDay) {
                    }
                }, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                datePickerDialog.setTitle(this.context.getString(R.string.date_select_title));
                datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, this.context.getString(R.string.sure),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                DatePicker mDatePicker = datePickerDialog.getDatePicker();
                                int mYear = mDatePicker.getYear();
                                int mMonth = mDatePicker.getMonth() + 1;
                                int mDay = mDatePicker.getDayOfMonth();
                                String dateStr = mYear + "-" + (mMonth >= 10 ? mMonth : ("0" + mMonth)) + "-" + (mDay >= 10 ? mDay : ("0" + mDay));
                                //顯示日期
                                tvShowDate.setText(DateUtil.getStrByDate(DateUtil.getDateByStr(dateStr)));
                                //星期顯示
                                String weekStr = DateUtil.getWeekByDate(DateUtil.getDateByStr(dateStr));
                                tvShowWeek.setText(weekStr);
                                dialogInterface.dismiss();
                            }
                        });
                datePickerDialog.setButton(DialogInterface.BUTTON_NEGATIVE, this.context.getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        });
                datePickerDialog.show();
                break;

            //日期減一天
            case R.id.date_select_btn_up:
                String dateStr = tvShowDate.getText().toString();
                Date date = DateUtil.getDateByStr(dateStr);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE,-1);

                tvShowDate.setText(DateUtil.getStrByDate(calendar.getTime()));

                String weekStr = DateUtil.getWeekByDate(calendar.getTime());
                tvShowWeek.setText(weekStr);

                break;

            //日期增加一天
            case R.id.date_select_btn_down:
                dateStr = tvShowDate.getText().toString();
                date = DateUtil.getDateByStr(dateStr);
                calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.add(Calendar.DATE,1);

                tvShowDate.setText(DateUtil.getStrByDate(calendar.getTime()));

                weekStr = DateUtil.getWeekByDate(calendar.getTime());
                tvShowWeek.setText(weekStr);
                break;
        }


    }
}

佈局檔案dialog_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialog_custom_layout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>
資原始檔attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 定義時間控制元件裡面的相關屬性 -->
    <declare-styleable name="date_select">
        <!-- 顯示時間的背景 -->
        
        <attr name="bg_color" format="reference|integer" />
      <!--   顯示日期 -->
        <attr name="tv_show_date_text" format="string" />
        <!--顯示星期  -->
        <attr name="tv_show_week_text" format="string" />
        <!-- 顯示字型的姿色 -->
        <attr name="tv_show_time_text_color" format="reference|integer" />
        <!-- 顯示字型的大小 -->
        <attr name="tv_show_time_text_size" format="reference|integer" />
        <!-- 顯示按鈕up背景 -->
        <attr name="btn_up_bg" format="reference|integer" />
        <!-- 顯示按鈕down背景 -->
        <attr name="btn_down_bg" format="reference|integer" />
        <!-- 是否隱藏兩個button -->
        <attr name="layout_visible" format="boolean" />
    </declare-styleable>

</resources>

時間轉換工具
DateUtil.java

public class DateUtil {
    private final static String TAG = DateUtil.class.getName();
    /*
     *根據日期獲取星期
     */
    public static String getWeekByDate(Date date){
        String[] weeks = {"週日","週一","週二","週三","週四","週五","週六"};
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int w = calendar.get(Calendar.DAY_OF_WEEK)-1;
        if (w<0) w = 0;
        return weeks[w];
    }

    /*
    *字條串轉換成日期
    */
    public static Date getDateByStr(String dateStr){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = simpleDateFormat.parse(dateStr);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date();
    }

    /*
    *日期轉換成字串
     */
    public static String getStrByDate(Date date){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.format(date);
    }
}

介面引用

<com.wecon.pa.view.widget.DateSelect
            android:id="@+id/main_date"
            android:layout_width="0px"
            android:layout_height="30px"
            android:layout_weight="2"
            lee:layout_visible="false"
            lee:btn_down_bg="@mipmap/down"
            lee:btn_up_bg="@mipmap/up"
            lee:tv_show_date_text="2018/09/29"
            lee:tv_show_time_text_color="@color/colorBlack"
            lee:tv_show_time_text_size="10"
            lee:tv_show_week_text="週一" />