1.導入Gson與okhttp
dependencies {
implementation 'com.contrarywind:Android-PickerView:4.1.9'
}
2.程式碼
package com.example.datepicker
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
private var year = mutableListOf<String>()
private var month = mutableListOf<String>()
private var day = mutableListOf<String>()
var nowYear: Int = 0
var nowMonth: Int = 0
var nowDay: Int = 0
lateinit var datePicker: OptionsPickerView<String>
lateinit var calendar : Calendar
@SuppressLint("SimpleDateFormat")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
calendar = Calendar.getInstance()
chocie.setOnClickListener {
year.clear()
month.clear()
day.clear()
getDate()
datePicker = OptionsPickerBuilder(this,
OnOptionsSelectListener { choiceYear, choiceMonth, choiceDay, _ ->
var newYear = (choiceYear+1).toString()
var newMonth = (choiceMonth+1).toString()
var newDay = (choiceDay+1).toString()
if (newYear.length < 3) {
newYear = "0newYear"
}
if (newMonth.length == 1) {
newMonth = "0newMonth"
}
if (newDay.length == 1) {
newDay = "0newDay"
}
date.text = "newYear/newMonth/newDay"
year.clear()
month.clear()
day.clear()
}).setOptionsSelectChangeListener { options1, options2, options3 ->
calendar.set(Calendar.YEAR, options1 + 1912)
calendar.set(Calendar.MONTH, options2)
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH))
val format = SimpleDateFormat("dd")
val endDate = format.format(calendar.time)
changeTheDay(endDate.toInt(), options1, options2, options3)
}
.setSubmitText("確定")
.setContentTextSize(20)
.build()
datePicker.setNPicker(year, month, day)
datePicker.setSelectOptions(nowYear, nowMonth -1 ,nowDay)
datePicker.show()
}
}
private fun getDate() {
nowYear = Calendar.getInstance().get(Calendar.YEAR) - 1911
Log.d("123", nowYear.toString())
for (i in 1..nowYear) {
year.add("民國{i}年")
}
nowMonth = Calendar.getInstance().get(Calendar.MONTH) + 1
for (i in 1..12) {
month.add("{i}月")
}
nowDay = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
for (i in 1..nowDay) {
day.add("{i}日")
}
}
private fun changeTheDay(thisDay: Int, options1: Int, options2: Int, options3: Int) {
day.clear()
for (i in 1..thisDay) {
day.add("i 日")
}
datePicker.setNPicker(year, month, day)
datePicker.setSelectOptions(options1, options2, options3)
}
}