DatePicker / NumberPicker

效果圖:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.example.mytoolutils.datepickAndnumberpick.DatepickerAndNumberpicker;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.widget.DatePicker;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.TextView;
import android.widget.DatePicker.OnDateChangedListener;

public class PickerActivity extends Activity implements OnValueChangeListener {
    private int Myear=0,MmonthOfYear=0,MdayOfMonth=0;
    private NumberPicker numberpicker1,numberpicker2;
    private TextView textView1,textView2;
    private SimpleDateFormat sFormat;
    private Date date;
    /** 中間分割線顏色*/
    private String halvinglineColor="#FF0000";
    /** 省份*/
    private String[] province={"黑龍江省","遼寧省","河南省","吉林省","山西省"," 青海省","山東省",
            "江蘇省","安徽省","福建省","江西省","湖南省","湖北省","廣東省"," 臺灣省","海南省"};
    /** 城市*/
    private String[][]city={
            {"哈爾濱","齊齊哈爾","雞西","鶴崗","雙鴨山","大慶","伊春","佳木斯","七臺河","牡丹江","黑河","綏化"},
            {"瀋陽","大連","鞍山","營口","盤錦","錦州","撫順","本溪","遼陽","丹東","葫蘆島","鐵嶺","朝陽","阜新"},
            {"鄭州","開封","洛陽","平頂山","安陽","鶴壁","新鄉","焦作","濮陽"," 許昌","漯河","三門峽","南陽","商丘","信陽","周口","駐馬店","濟源"},
            {"長春","九臺","榆樹","德惠","吉林","蛟河","樺甸","舒蘭","磐石","四平","公主嶺","雙遼","遼源",
                "通化","梅河口","集安","白山","臨江","松原","白城","洮南","大安","延吉","圖們","敦化","琿春","龍井","和龍 "},
            {"太原","大同","陽泉","長治","晉城","朔州","晉中","運城","忻州","臨汾","呂梁 "},
            {"西寧 ","格爾木","西寧","玉樹","果洛","海東","海西","海南","海北"},
            {"濟南","青島","淄博","棗莊","東營","煙臺","濰坊","濟寧","泰安","威海","日照","萊蕪","臨沂","德州","聊城","濱州","荷澤"},
            {"南京","無錫","徐州","常州","蘇州","南通","連雲港","淮安","鹽城","揚州","鎮江","泰州","宿遷 "},
            {"合肥","蕪湖","蚌埠","淮南","馬鞍山","淮北","銅陵","安慶","桐城","黃山","滁州","天長","明光","阜陽","界首","宿州","巢湖","六安","亳州","池州","宣城","寧國"},
            {"福州","廈門","莆田","三明","泉州","漳州","南平","龍巖","寧德"},
            {"南昌","九江","上饒","撫州","宜春","吉安","贛州","景德鎮","萍鄉","新餘","鷹潭","樂平","瑞昌","貴溪","南康","豐城","樟樹","高安","德興","臨川"," 瑞金","井岡山"},
            {"長沙","株洲","湘潭","衡陽","邵陽","岳陽","常德","張家界","益陽","郴洲","永州","懷化","婁底"},
            {"武漢","黃石","十堰","荊州","宜昌","襄樊","鄂州","荊門","孝感","黃岡","咸寧","隨州"},
            {"廣州","深圳","珠海","汕頭","佛山","韶關","湛江","肇慶","江門","茂名","惠州","梅州","汕尾","河源","陽江","清遠","東莞","中山","潮州","揭陽","雲浮 ,"
                    + "增城","從化","南雄","樂昌","英德","連州","台山","開平","鶴山","恩平","廉江","雷州","吳川","高州","化州","信宜","高要","四會","興寧","陸豐","陽春","普寧","羅定 "},
            {"臺北","高雄","基隆","臺中","臺南","新竹","嘉義"},
            {"海口","三亞","瓊海","文昌","萬寧","儋州","東方","五指山"}};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picker);
        initview();
        initDate();
        initNumber();
    }
    private void initview() {
        textView1=(TextView) findViewById(R.id.textview1);
        textView2=(TextView) findViewById(R.id.textview2);
        textView2.setText(city[0][0]);
    }
    /**
     * set numberpicker
     */
    private void initNumber() {
        numberpicker1=(NumberPicker) findViewById(R.id.numberpicker1);
        numberpicker2=(NumberPicker) findViewById(R.id.numberpicker2);
        //加載數據
        DatepickerAndNumberpicker.SetNumberPicker(numberpicker1, province, halvinglineColor);
        DatepickerAndNumberpicker.SetNumberPicker(numberpicker2, city[0], halvinglineColor);
        //set lister
        numberpicker1.setOnValueChangedListener(this);
        numberpicker2.setOnValueChangedListener(this);
    }
    /**
     * set datepicker
     */
    @SuppressLint("SimpleDateFormat")
    private void initDate() {
        DatePicker datePicker=(DatePicker)findViewById(R.id.datapicker);
        DatepickerAndNumberpicker.SetDatePicker(datePicker, halvinglineColor);

        Calendar cal = Calendar.getInstance();
        int year=cal.get(Calendar.YEAR);
        int monthOfYear=cal.get(Calendar.MONTH);
        int dayOfMonth=cal.get(Calendar.DAY_OF_MONTH);
        sFormat = new SimpleDateFormat("yyyy-MM-dd"); 
        datePicker.init(year, monthOfYear, dayOfMonth, new OnDateChangedListener() {

            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                Myear=year;
                MmonthOfYear=++monthOfYear;
                MdayOfMonth=dayOfMonth;
                try {
                    date = sFormat.parse(Myear+"-"+MmonthOfYear+"-"+MdayOfMonth);
                    textView1.setText(DateFormat.format("yyyy-MM-dd", date));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private int cityone=0;
    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        switch (picker.getId()) {
        case R.id.numberpicker1:
            cityone=newVal;
            int oldlen=city[oldVal].length;
            int newlen=city[newVal].length;
            //調整最大值 避免越界
            if(oldlen<=newlen){
                numberpicker2.setMaxValue(city[oldVal].length-1);
            }else{
                numberpicker2.setMaxValue(city[newVal].length-1);
            }
            //加載數據
            numberpicker2.setDisplayedValues(city[newVal]);
            //設置靜態情況
            textView2.setText(city[newVal][0]);
            break;
        case R.id.numberpicker2:
            String nowcityname=city[cityone][newVal].toString();
            textView2.setText(nowcityname);
            break;
        default:
            break;
        }
    }
}

DatepickerAndNumberpicker,使用了HalvingLineUtils工具類,修改中間分割線顏色:

import android.annotation.SuppressLint;
import android.widget.DatePicker;
import android.widget.NumberPicker;

/**
 * set datepicker and numberpicker 
 *
 */
public class DatepickerAndNumberpicker {
    /**
     * 設置datepick
     * @param datePicker
     * @param String halvinglineColor 設置分割線顏色 可設爲null
     */
    @SuppressLint("SimpleDateFormat")
    public static void SetDatePicker(DatePicker datePicker,String halvinglineColor){
        //不可編輯
        datePicker.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
         //設置是否顯示CalendarView
        datePicker.setCalendarViewShown(false);
        //設置中間間隔線顏色
        if(halvinglineColor!=null&&!halvinglineColor.equals("")){
            HalvingLineUtils.setDatePickerDividerColor(datePicker,halvinglineColor);
        }
    }
    /**
     * 設置NumberPicker
     * 多級聯動 通過設置setDisplayedValues();
     * @param numberpicker
     * @param String[]data
     * @param halvinglineColor 設置分割線顏色 可設爲null
     */
    @SuppressLint("NewApi")
    public static void SetNumberPicker(NumberPicker numberpicker,String[]data,String halvinglineColor){
        numberpicker.setDisplayedValues(data);//加載數據
        numberpicker.setMinValue(0);//設置最小顯示下標
        numberpicker.setMaxValue(data.length-1);//設置最大顯示下標
        numberpicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);//不可編輯
        if(halvinglineColor!=null&&!halvinglineColor.equals("")){
            HalvingLineUtils.setNumberPickerDividerColor(numberpicker,halvinglineColor);
        }
    }
}

R.layout.activity_picker:

<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:gravity="center"
    android:orientation="vertical"
    tools:context="com.example.mytoolutils.PickerActivity" >

    <DatePicker
        android:id="@+id/datapicker"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/textview1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.2"
        android:gravity="center" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <NumberPicker
            android:id="@+id/numberpicker1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginRight="5dp"
            android:layout_weight="1" />

        <NumberPicker
            android:id="@+id/numberpicker2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="5dp"
            android:layout_weight="1" />
    </LinearLayout>

    <TextView
        android:id="@+id/textview2"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.2"
        android:gravity="center" />

</LinearLayout>
發佈了75 篇原創文章 · 獲贊 38 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章