函數System.currentTimeMillis()可取得當前系統時間
但此格式爲自1970/01/01 00:00:00.000到當前時間的毫秒
使用爲SimpleDateFormat加上對應的pattern,對System.currentTimeMillis()做format
而且format後就是String格式
tv_currentTime.text = SimpleDateFormat("MM月dd日 HH:MM").format(System.currentTimeMillis())
若希望個位數的月/日前面不要顯示0,可以改用Calendar直接取得Int再轉toString()
不過要注意Calendar.MONTH的12個月是從0-11,所以須再加1
val calendar = Calendar.getInstance()
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
tv_currentTime.text =
(month + 1).toString() + "月" + day.toString() + "日" + SimpleDateFormat(" HH:MM").format(
System.currentTimeMillis()
)
先簡單用個自訂的editText確認一下資料可取出
要在上方的action bar建立search,須要先建立屬於menu的xml
在layout新增resource,file跟directory name都使用menu
定義menu中的內容search item
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".ui.home.activities.TransactionSearchActivity">
<item
android:id="@+id/action_search"
android:icon="@android:drawable/ic_menu_search"
android:title="Search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always" />
</menu>
預覽
然後要在MainActivity override onCreateOptionsMenu
再建立searchView的object也須要override二個函數
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu,menu)
val searchItem = menu?.findItem(R.id.action_search)
if(searchItem != null){
val searchView = searchItem.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
TODO("Not yet implemented")
}
override fun onQueryTextChange(newText: String?): Boolean {
TODO("Not yet implemented")
}
})
}
return super.onCreateOptionsMenu(menu)
}
這樣就不用editText了,把搜尋的程式寫入onQueryTextChange()中
override fun onQueryTextChange(newText: String?): Boolean {
if(newText!!.isNotEmpty()){
val search = newText
weatherList.forEach {
if (it.locationName.contains(search)) {
tv_city.text = it.toString()
}
}
}
return true
}
參考
https://developer.android.com/guide/topics/search/search-dialog.html
https://medium.com/@prasanthvel/android-searchview-in-actionbar-androidx-and-kotlin-3467ca8e6a14