代码提交
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package com.shuwei.intelligent.shelves
|
||||
|
||||
import android.app.Application
|
||||
|
||||
/**
|
||||
* @author: star
|
||||
* @date: 2022-04-26
|
||||
*/
|
||||
class App : Application() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
app = this
|
||||
}
|
||||
|
||||
companion object {
|
||||
private lateinit var app: App
|
||||
|
||||
fun get(): App {
|
||||
return app
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package com.shuwei.intelligent.shelves
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.util.SparseIntArray
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||
import com.shuwei.intelligent.shelves.adapter.ShelfAdapter
|
||||
import com.shuwei.intelligent.shelves.base.BaseActivity
|
||||
import com.shuwei.intelligent.shelves.databinding.ActivityHomeBinding
|
||||
import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||
import com.shuwei.intelligent.shelves.serial.SerialPortManager
|
||||
import com.shuwei.intelligent.shelves.task.TaskManager
|
||||
import com.shuwei.intelligent.shelves.utils.UIUtils
|
||||
import com.shuwei.intelligent.shelves.utils.hexToDec
|
||||
import kotlinx.coroutines.launch
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
class HomeActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "HomeActivity"
|
||||
|
||||
//协议头
|
||||
const val HEADER = "D6DADEDB"
|
||||
|
||||
//协议尾
|
||||
const val FOOTER = "FFFF"
|
||||
const val ACTIVE_CMD =
|
||||
"${HEADER}000281C5D70A7D428A4FA67B50F7DACA241938938B4B9CBD73673E9C8E7F2E15062D${FOOTER}"
|
||||
|
||||
const val LEFT_SHELF_OPEN_CMD =
|
||||
"${HEADER}020101000000000000000000000000000000000000${FOOTER}"
|
||||
const val RIGHT_SHELF_OPEN_CMD =
|
||||
"${HEADER}020100010000000000000000000000000000000000${FOOTER}"
|
||||
|
||||
//const val TEMPERATURE_CMD = "${HEADER}1001${FOOTER}"
|
||||
|
||||
const val DEVICE_INFO_CMD = "${HEADER}0301000000000000000000000000${FOOTER}"
|
||||
|
||||
val list: MutableList<ShelfModel> = mutableListOf()
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivityHomeBinding
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityHomeBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
|
||||
updateLeftStatus("1-1冷藏柜 -2°C / 87%")
|
||||
|
||||
initList()
|
||||
initRecyclerView()
|
||||
|
||||
lifecycleScope.launch {
|
||||
val openState = SerialPortManager.open()
|
||||
Log.d(TAG, "onCreate: openState=$openState")
|
||||
if (openState) {
|
||||
SerialPortManager.startReceive { data ->
|
||||
runOnUiThread {
|
||||
// 更新UI显示接收数据
|
||||
receiveSerialPortData(data)
|
||||
}
|
||||
}
|
||||
SerialPortManager.send(ACTIVE_CMD)
|
||||
}
|
||||
}
|
||||
TaskManager.startTask()
|
||||
}
|
||||
|
||||
private fun receiveSerialPortData(data: String) {
|
||||
Log.d(TAG, "receiveSerialPortData: $data")
|
||||
if (data.startsWith(HEADER).not()) {
|
||||
return
|
||||
}
|
||||
val cmd = data.substring(HEADER.length, HEADER.length + 2)
|
||||
when (cmd) {
|
||||
"03" -> {
|
||||
//获取设备状态
|
||||
val weightStartIndex = HEADER.length + 4 + 10
|
||||
val temperatureStartIndex = weightStartIndex + 10 * 8
|
||||
val temperatureHex = data.substring(temperatureStartIndex, 2)
|
||||
val temperature = hexToDec(temperatureHex)
|
||||
updateLeftStatus("1-1冷藏柜 $temperature°C / 87%")
|
||||
|
||||
var index = 1
|
||||
var count = weightStartIndex
|
||||
while (count < temperatureStartIndex) {
|
||||
val weightInfo = data.substring(count, count + 8)
|
||||
var weightHex = ""
|
||||
weightInfo.run {
|
||||
weightHex =
|
||||
substring(6, 8) + substring(4, 6) + substring(2, 4) + substring(0, 2)
|
||||
}
|
||||
var realWeight = 0
|
||||
if (weightHex.first() in '8'..'F') {
|
||||
//负数
|
||||
val weightHex2 = "0${weightHex.substring(1)}"
|
||||
realWeight = hexToDec(weightHex2)
|
||||
} else {
|
||||
//整数
|
||||
realWeight = hexToDec(weightHex)
|
||||
}
|
||||
weightArray.put(count, realWeight)
|
||||
count += 8
|
||||
index++
|
||||
}
|
||||
|
||||
val intent = Intent(ShelfActivity.RECEIVER_DEVICE_INFO)
|
||||
intent.putExtra(ShelfActivity.SHELF_WEIGHT, weightArray[clickIndex])
|
||||
sendBroadcast(intent)
|
||||
}
|
||||
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
|
||||
private val weightArray by lazy { SparseIntArray() }
|
||||
private var clickIndex = 0
|
||||
|
||||
override fun onDestroy() {
|
||||
lifecycleScope.launch {
|
||||
SerialPortManager.close()
|
||||
}
|
||||
TaskManager.cancelTask()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private val shelfAdapter by lazy {
|
||||
// val list = viewModel.getCurrentItems()
|
||||
ShelfAdapter(list).apply {
|
||||
setOnDebouncedItemClick { adapter, view, position ->
|
||||
this@HomeActivity.clickIndex = position
|
||||
lifecycleScope.launch {
|
||||
val openCmd = if (list[position].shelfNo in 1..5)
|
||||
LEFT_SHELF_OPEN_CMD
|
||||
else
|
||||
RIGHT_SHELF_OPEN_CMD
|
||||
val openState = SerialPortManager.send(openCmd)
|
||||
if (openState.not()) {
|
||||
UIUtils.toast("${list[position].foodName}柜门开启失败")
|
||||
return@launch
|
||||
}
|
||||
launch(Intent(this@HomeActivity, ShelfActivity::class.java).also {
|
||||
it.putExtra(ShelfActivity.SHELF_MODEL, list[position])
|
||||
}) {
|
||||
it?.run {
|
||||
val model =
|
||||
getSerializableExtra(ShelfActivity.SHELF_MODEL) as ShelfModel
|
||||
list[position].apply {
|
||||
foodName = model.foodName
|
||||
foodWeight = model.foodWeight
|
||||
storeDate = model.storeDate
|
||||
}
|
||||
notifyItemChanged(position)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun initRecyclerView() {
|
||||
binding.rvShelf.run {
|
||||
layoutManager =
|
||||
GridLayoutManager(this@HomeActivity, 2, GridLayoutManager.VERTICAL, false)
|
||||
adapter = shelfAdapter
|
||||
}
|
||||
}
|
||||
|
||||
private fun initList() {
|
||||
// val list: MutableList<ShelfModel> = mutableListOf()
|
||||
list.add(ShelfModel(shelfNo = 1))
|
||||
list.add(ShelfModel(shelfNo = 6))
|
||||
list.add(ShelfModel(shelfNo = 2))
|
||||
list.add(ShelfModel(shelfNo = 7))
|
||||
list.add(ShelfModel(shelfNo = 3))
|
||||
list.add(ShelfModel(shelfNo = 8))
|
||||
list.add(ShelfModel(shelfNo = 4))
|
||||
list.add(ShelfModel(shelfNo = 9))
|
||||
list.add(ShelfModel(shelfNo = 5))
|
||||
list.add(ShelfModel(shelfNo = 10))
|
||||
// viewModel.updateItems(list)
|
||||
}
|
||||
|
||||
private val MM_DD_EEEE__HH_MM_SS = "MM月dd日 EEEE HH:mm:ss"
|
||||
|
||||
private fun updateDateTime() {
|
||||
val sdf = SimpleDateFormat(MM_DD_EEEE__HH_MM_SS, Locale.CHINA)
|
||||
val dateTime = sdf.format(Date())
|
||||
updateRightStatus(dateTime)
|
||||
}
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val updateTask = object : Runnable {
|
||||
override fun run() {
|
||||
updateDateTime()
|
||||
handler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
hideStatusBar()
|
||||
handler.post(updateTask)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
handler.removeCallbacks(updateTask)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package com.shuwei.intelligent.shelves
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.annotation.RequiresApi
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.recyclerview.widget.GridLayoutManager
|
||||
import com.chad.library.adapter4.util.setOnDebouncedItemClick
|
||||
import com.shuwei.intelligent.shelves.HomeActivity.Companion.ACTIVE_CMD
|
||||
import com.shuwei.intelligent.shelves.HomeActivity.Companion.DEVICE_INFO_CMD
|
||||
import com.shuwei.intelligent.shelves.utils.ext.addOnActionSearchListener
|
||||
import com.shuwei.intelligent.shelves.utils.ext.clickWithDebounce
|
||||
import com.shuwei.intelligent.shelves.utils.ext.toast
|
||||
import com.shuwei.intelligent.shelves.adapter.SearchAdapter
|
||||
import com.shuwei.intelligent.shelves.base.BaseActivity
|
||||
import com.shuwei.intelligent.shelves.databinding.ActivityShelfBinding
|
||||
import com.shuwei.intelligent.shelves.model.SearchModel
|
||||
import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||
import com.shuwei.intelligent.shelves.serial.SerialPortManager
|
||||
import com.shuwei.intelligent.shelves.utils.DateTimeUtil
|
||||
import com.shuwei.intelligent.shelves.utils.KeyboardUtil
|
||||
import com.shuwei.intelligent.shelves.utils.decToHex
|
||||
import kotlinx.coroutines.launch
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import kotlin.random.Random
|
||||
|
||||
@SuppressLint("NotifyDataSetChanged")
|
||||
class ShelfActivity : BaseActivity() {
|
||||
|
||||
companion object {
|
||||
const val SHELF_MODEL = "shelfModel"
|
||||
const val RECEIVER_DEVICE_INFO = "receiverDeviceInfo"
|
||||
const val SHELF_WEIGHT = "shelfWeight"
|
||||
|
||||
}
|
||||
|
||||
private lateinit var binding: ActivityShelfBinding
|
||||
|
||||
private var shelfModel: ShelfModel? = null
|
||||
|
||||
private var clickIndex: Int = -1
|
||||
|
||||
private var realWeight: Int = 0
|
||||
|
||||
@SuppressLint("UnspecifiedRegisterReceiverFlag")
|
||||
@Suppress("DEPRECATION")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityShelfBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
|
||||
shelfModel = intent.getSerializableExtra(SHELF_MODEL) as ShelfModel?
|
||||
|
||||
shelfModel?.let {
|
||||
binding.tvShelfName.text = it.shelfName
|
||||
binding.tvFoodName.text = if (it.foodName.isNullOrBlank()) "-" else it.foodName
|
||||
}
|
||||
|
||||
initRecyclerView()
|
||||
// initWeight()
|
||||
binding.etInputFood.run {
|
||||
addOnActionSearchListener {
|
||||
if (text.isNullOrBlank()) {
|
||||
toast(hint.toString())
|
||||
return@addOnActionSearchListener
|
||||
}
|
||||
loadSearchData()
|
||||
KeyboardUtil.hideKeyboard(context, this)
|
||||
}
|
||||
}
|
||||
|
||||
binding.btnConfirm.clickWithDebounce {
|
||||
if (clickIndex < 0) {
|
||||
toast("请选择食材")
|
||||
return@clickWithDebounce
|
||||
}
|
||||
val data = ShelfModel(
|
||||
shelfName = shelfModel?.shelfName,
|
||||
foodName = list[clickIndex].foodName,
|
||||
foodWeight = realWeight,
|
||||
storeDate = DateTimeUtil.formatDateTime(dateTime = Date())
|
||||
)
|
||||
val intent = Intent().apply {
|
||||
putExtra(SHELF_MODEL, data)
|
||||
}
|
||||
setResult(RESULT_OK, intent)
|
||||
finish()
|
||||
}
|
||||
binding.tvFoodWeight.text = "${realWeight}克"
|
||||
binding.root.setOnClickListener { v ->
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
}
|
||||
binding.btnClearZero.setOnClickListener { v ->
|
||||
lifecycleScope.launch {
|
||||
val shelfNo = shelfModel?.shelfNo ?: 0
|
||||
val zeroClearingCmd =
|
||||
"${HomeActivity.HEADER}0401${decToHex(shelfNo)}${HomeActivity.FOOTER}"
|
||||
SerialPortManager.send(zeroClearingCmd)
|
||||
}
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
}
|
||||
|
||||
lifecycleScope.launch {
|
||||
SerialPortManager.send(DEVICE_INFO_CMD)
|
||||
}
|
||||
|
||||
registerReceiver(receiver, IntentFilter(RECEIVER_DEVICE_INFO))
|
||||
}
|
||||
|
||||
private val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) {
|
||||
intent?.let {
|
||||
realWeight = it.getIntExtra(SHELF_WEIGHT, 0)
|
||||
binding.tvFoodWeight.text = "${realWeight}克"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
unregisterReceiver(receiver)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
// private fun initWeight() {
|
||||
// realWeight = Random.nextInt(1, 5001)
|
||||
// }
|
||||
|
||||
private fun loadSearchData() {
|
||||
list.add(SearchModel(foodId = 1000, foodName = "菲律宾乳猪五花肉"))
|
||||
list.add(SearchModel(foodId = 1001, foodName = "金针菇"))
|
||||
list.add(SearchModel(foodId = 1002, foodName = "大菠菜"))
|
||||
list.add(SearchModel(foodId = 1003, foodName = "清远麻鸡块"))
|
||||
list.add(SearchModel(foodId = 1004, foodName = "普罗旺斯番茄"))
|
||||
list.add(SearchModel(foodId = 1005, foodName = "长条茄子"))
|
||||
list.add(SearchModel(foodId = 1006, foodName = "得莫利鱼"))
|
||||
list.add(SearchModel(foodId = 1007, foodName = "土豆丝"))
|
||||
list.add(SearchModel(foodId = 1008, foodName = "辣椒炒肉"))
|
||||
list.add(SearchModel(foodId = 1009, foodName = "雪菜烧豆腐"))
|
||||
list.add(SearchModel(foodId = 1010, foodName = "冬虫夏草炝拌芥兰苗"))
|
||||
list.add(
|
||||
SearchModel(
|
||||
foodId = 1011,
|
||||
foodName = "蘑菇玉米山药莲藕胡萝卜红枣莲子枸杞清炖排骨汤"
|
||||
)
|
||||
)
|
||||
searchAdapter.notifyDataSetChanged()
|
||||
}
|
||||
|
||||
private val list: MutableList<SearchModel> = mutableListOf()
|
||||
private val searchAdapter by lazy {
|
||||
SearchAdapter(list).apply {
|
||||
setOnDebouncedItemClick { adapter, v, position ->
|
||||
this@ShelfActivity.clickIndex = position
|
||||
list.forEach { it.isClicked = false }
|
||||
list[position].isClicked = true
|
||||
notifyDataSetChanged()
|
||||
binding.tvFoodName.text = list[position].foodName
|
||||
KeyboardUtil.hideKeyboard(v.context, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun initRecyclerView() {
|
||||
binding.rvSearch.run {
|
||||
layoutManager = GridLayoutManager(this@ShelfActivity, 2)
|
||||
adapter = searchAdapter
|
||||
}
|
||||
}
|
||||
|
||||
private val YYYY_MM_DD__EEEE_HH_MM_SS = "yyyy年MM月dd日 EEEE***HH:mm:ss"
|
||||
|
||||
private fun updateDateTime() {
|
||||
val sdf = SimpleDateFormat(YYYY_MM_DD__EEEE_HH_MM_SS, Locale.CHINA)
|
||||
val dateTime = sdf.format(Date())
|
||||
val arr = dateTime.split("***")
|
||||
updateLeftStatus(arr[0])
|
||||
updateRightStatus(arr[1])
|
||||
}
|
||||
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val updateTask = object : Runnable {
|
||||
override fun run() {
|
||||
updateDateTime()
|
||||
handler.postDelayed(this, 1000)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
hideStatusBar()
|
||||
handler.post(updateTask)
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
handler.removeCallbacks(updateTask)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.shuwei.intelligent.shelves.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.content.res.ColorStateList
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.annotation.ColorRes
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.core.graphics.toColorInt
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.intelligent.shelves.R
|
||||
import com.shuwei.intelligent.shelves.databinding.ListItemSearchBinding
|
||||
import com.shuwei.intelligent.shelves.model.SearchModel
|
||||
|
||||
class SearchAdapter(list: MutableList<SearchModel>) :
|
||||
BaseQuickAdapter<SearchModel, SearchAdapter.VH>(list) {
|
||||
|
||||
inner class VH(var binding: ListItemSearchBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||
val inflater = LayoutInflater.from(context)
|
||||
val binding = ListItemSearchBinding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: SearchModel?) {
|
||||
val binding = holder.binding
|
||||
binding.btnFoodName.run {
|
||||
text = item!!.foodName
|
||||
setTextColor(
|
||||
getColor(if (item.isClicked) R.color.shelf_name_blue else R.color.black999)
|
||||
)
|
||||
val btnStrokeColor = if (item.isClicked) "#4969F5" else "#E6E6E6"
|
||||
strokeColor = ColorStateList.valueOf(btnStrokeColor.toColorInt())
|
||||
}
|
||||
// val bgDrawable = createCustomDrawable(
|
||||
// solidColor = "#FFFFFF",
|
||||
// strokeWidth = 2.dp,
|
||||
// strokeColor = if (item!!.isClicked) "#4969F5" else "#E6E6E6",
|
||||
// radius = 12.dp
|
||||
// )
|
||||
// binding.root.background = bgDrawable
|
||||
|
||||
}
|
||||
|
||||
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package com.shuwei.intelligent.shelves.adapter
|
||||
|
||||
import android.content.Context
|
||||
import android.view.LayoutInflater
|
||||
import android.view.ViewGroup
|
||||
import androidx.annotation.ColorRes
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.chad.library.adapter4.BaseQuickAdapter
|
||||
import com.chad.library.adapter4.viewholder.QuickViewHolder
|
||||
import com.shuwei.intelligent.shelves.R
|
||||
import com.shuwei.intelligent.shelves.databinding.ListItemShelfBinding
|
||||
import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||
|
||||
class ShelfAdapter(list: MutableList<ShelfModel>) :
|
||||
BaseQuickAdapter<ShelfModel, ShelfAdapter.VH>(list) {
|
||||
|
||||
inner class VH(var binding: ListItemShelfBinding) : QuickViewHolder(binding.root)
|
||||
|
||||
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
|
||||
val inflater = LayoutInflater.from(context)
|
||||
val binding = ListItemShelfBinding.inflate(inflater, parent, false)
|
||||
return VH(binding)
|
||||
}
|
||||
|
||||
override fun onBindViewHolder(holder: VH, position: Int, item: ShelfModel?) {
|
||||
val shelfNo = item!!.shelfNo
|
||||
item.shelfName = "货架-${if (shelfNo < 10) "0${shelfNo}" else "$shelfNo" }"
|
||||
val weight = item.foodWeight ?: 0
|
||||
val binding = holder.binding
|
||||
val isBlankShelf = weight <= 0
|
||||
if (isBlankShelf) {
|
||||
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_blue))
|
||||
binding.tvShelfName.run {
|
||||
setTextColor(getColor(R.color.shelf_name_white))
|
||||
text = item.shelfName
|
||||
}
|
||||
binding.tvFoodName.run {
|
||||
setTextColor(getColor(R.color.white))
|
||||
text = "空"
|
||||
}
|
||||
binding.tvFoodWeight.run {
|
||||
setTextColor(getColor(R.color.food_weight_blue))
|
||||
text = "0千克"
|
||||
}
|
||||
binding.tvStoreDate.run {
|
||||
setTextColor(getColor(R.color.food_weight_blue))
|
||||
text = "-"
|
||||
}
|
||||
return
|
||||
}
|
||||
binding.layoutCard.setCardBackgroundColor(getColor(R.color.bg_card_white))
|
||||
binding.tvShelfName.run {
|
||||
setTextColor(getColor(R.color.shelf_name_blue))
|
||||
text = item.shelfName
|
||||
}
|
||||
binding.tvFoodName.run {
|
||||
setTextColor(getColor(R.color.food_name_black))
|
||||
text = item.foodName
|
||||
}
|
||||
binding.tvFoodWeight.run {
|
||||
setTextColor(getColor(R.color.food_weight_orange))
|
||||
text = "${weight/1000F}千克"
|
||||
}
|
||||
binding.tvStoreDate.run {
|
||||
setTextColor(getColor(R.color.black999))
|
||||
text = item.storeDate
|
||||
}
|
||||
}
|
||||
|
||||
private fun getColor(@ColorRes id: Int) = ContextCompat.getColor(context, id)
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package com.shuwei.intelligent.shelves.base
|
||||
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.view.View
|
||||
import android.widget.TextView
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.shuwei.intelligent.shelves.R
|
||||
import com.shuwei.intelligent.shelves.databinding.ActivityBaseBinding
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
open class BaseActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var binding: ActivityBaseBinding
|
||||
private var launcher: ActivityResultLauncher<Intent>? = null
|
||||
private var launchCallback: ((Intent?) -> Unit)? = null
|
||||
|
||||
public fun launch(cls: Class<*>, launchCallback: (Intent?) -> Unit) {
|
||||
this.launchCallback = launchCallback
|
||||
launcher?.launch(Intent(this, cls))
|
||||
}
|
||||
|
||||
public fun launch(intent: Intent, launchCallback: (Intent?) -> Unit) {
|
||||
this.launchCallback = launchCallback
|
||||
launcher?.launch(intent)
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
binding = ActivityBaseBinding.inflate(layoutInflater)
|
||||
setContentView(binding.root)
|
||||
statusBarDarkFont(enable = false)
|
||||
launcher =
|
||||
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
if (result.resultCode == RESULT_OK) {
|
||||
launchCallback?.invoke(result.data)
|
||||
}
|
||||
}
|
||||
|
||||
// window.setDecorFitsSystemWindows(false) // 启用 Edge-to-Edge
|
||||
// window.insetsController?.apply {
|
||||
// hide(WindowInsets.Type.statusBars()) // 隐藏状态栏
|
||||
// systemBarsBehavior =
|
||||
// WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE // 滑动时临时显示
|
||||
// }
|
||||
}
|
||||
|
||||
fun hideStatusBar() {
|
||||
enableEdgeToEdge()
|
||||
// val uiOptions = (View.SYSTEM_UI_FLAG_FULLSCREEN // 隐藏状态栏
|
||||
// or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) // 隐藏导航栏(可选)
|
||||
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_FULLSCREEN
|
||||
}
|
||||
|
||||
fun statusBarDarkFont(enable: Boolean) {
|
||||
//window.decorView.systemUiVisibility = if (enable) View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
|
||||
val color = ContextCompat.getColor(this, R.color.white)
|
||||
binding.tvLeftStatus.setTextColor(color)
|
||||
binding.tvRightStatus.setTextColor(color)
|
||||
}
|
||||
|
||||
override fun setContentView(view: View?) {
|
||||
if (view == binding.root) {
|
||||
super.setContentView(view)
|
||||
} else {
|
||||
binding.flContainer.addView(view)
|
||||
}
|
||||
}
|
||||
|
||||
fun updateLeftStatus(data: String) {
|
||||
binding.tvLeftStatus.text = data
|
||||
}
|
||||
|
||||
fun updateRightStatus(data: String) {
|
||||
binding.tvRightStatus.text = data
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.shuwei.intelligent.shelves.model
|
||||
|
||||
import java.io.Serializable
|
||||
|
||||
data class SearchModel(
|
||||
var foodId: Int? = null,
|
||||
var foodName: String? = null,
|
||||
var isClicked: Boolean = false
|
||||
) : Serializable
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.shuwei.intelligent.shelves.model
|
||||
|
||||
import java.io.Serializable
|
||||
|
||||
data class ShelfModel(
|
||||
var shelfNo: Int = 0,
|
||||
var shelfName: String? = null,
|
||||
var foodName: String? = null,
|
||||
var foodWeight: Int? = null,
|
||||
var storeDate: String? = null
|
||||
) : Serializable
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.shuwei.intelligent.shelves.serial
|
||||
|
||||
import io.github.jeadyx.jserialport.AndroidSerialPort
|
||||
import io.github.jeadyx.jserialport.SerialPort
|
||||
import io.github.jeadyx.jserialport.SerialPortFactory
|
||||
import kotlinx.coroutines.*
|
||||
|
||||
object SerialPortManager {
|
||||
private const val portName: String = "/dev/ttyS1"
|
||||
private const val baudRate: Int = 115200
|
||||
private var serialPort: AndroidSerialPort? = null
|
||||
// private var serialPort: SerialPort? = null
|
||||
private val scope = CoroutineScope(Dispatchers.IO)
|
||||
|
||||
// 打开串口
|
||||
suspend fun open(): Boolean {
|
||||
return try {
|
||||
serialPort = SerialPortFactory.create().apply {
|
||||
open(
|
||||
portName = portName,
|
||||
baudRate = baudRate,
|
||||
dataBits = 8,
|
||||
stopBits = 1,
|
||||
parity = SerialPort.PARITY_NONE
|
||||
)
|
||||
} as AndroidSerialPort?
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// 发送数据
|
||||
suspend fun send(data: String): Boolean {
|
||||
return try {
|
||||
serialPort?.write(data.toByteArray())
|
||||
true
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// 启动接收协程
|
||||
fun startReceive(callback: (String) -> Unit) {
|
||||
scope.launch {
|
||||
while (isActive) {
|
||||
serialPort?.read()?.collect { buffer ->
|
||||
callback(String(buffer))
|
||||
}
|
||||
delay(50)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭串口
|
||||
suspend fun close() {
|
||||
scope.cancel()
|
||||
serialPort?.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.shuwei.intelligent.shelves.task
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.work.CoroutineWorker
|
||||
import androidx.work.WorkerParameters
|
||||
import com.shuwei.intelligent.shelves.HomeActivity
|
||||
import com.shuwei.intelligent.shelves.utils.ext.toJsonString
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class SyncTask(appContext: Context, workerParams: WorkerParameters) :
|
||||
CoroutineWorker(appContext, workerParams) {
|
||||
|
||||
companion object {
|
||||
private const val TAG = "SyncTask"
|
||||
}
|
||||
|
||||
override suspend fun doWork(): Result {
|
||||
return try {
|
||||
// 执行后台任务逻辑
|
||||
performSync()
|
||||
|
||||
TaskManager.startTask()
|
||||
|
||||
Result.success()
|
||||
} catch (e: Exception) {
|
||||
e.printStackTrace()
|
||||
Result.retry()
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun performSync() {
|
||||
withContext(Dispatchers.IO) {
|
||||
val list = HomeActivity.list
|
||||
Log.d(TAG, "performSync: list:${list.toJsonString()}")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.shuwei.intelligent.shelves.task
|
||||
|
||||
import androidx.work.ExistingWorkPolicy
|
||||
import androidx.work.OneTimeWorkRequestBuilder
|
||||
import androidx.work.WorkManager
|
||||
import com.shuwei.intelligent.shelves.App
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
object TaskManager {
|
||||
const val TASK_NAME = "IntelligentShelvesSyncTask"
|
||||
|
||||
fun startTask() {
|
||||
val nextRequest = OneTimeWorkRequestBuilder<SyncTask>()
|
||||
.setInitialDelay(3, TimeUnit.MINUTES)
|
||||
// .setInitialDelay(10, TimeUnit.SECONDS)
|
||||
// .setInputData(inputData)
|
||||
.build()
|
||||
WorkManager.getInstance(App.get())
|
||||
.enqueueUniqueWork(TASK_NAME, ExistingWorkPolicy.REPLACE, nextRequest)
|
||||
|
||||
// val constraints = Constraints.Builder()
|
||||
// .setRequiredNetworkType(NetworkType.CONNECTED)
|
||||
// .setRequiresBatteryNotLow(true)
|
||||
// .build()
|
||||
// val syncRequest = PeriodicWorkRequestBuilder<SyncTask>(
|
||||
// 3L, TimeUnit.MINUTES, // 最小间隔15分钟
|
||||
// 3L, TimeUnit.MINUTES // 弹性时间窗口
|
||||
// )
|
||||
// .setConstraints(constraints)
|
||||
// .build()
|
||||
// WorkManager.getInstance(App.get())
|
||||
// .enqueueUniquePeriodicWork(
|
||||
// TASK_NAME,
|
||||
// ExistingPeriodicWorkPolicy.KEEP,
|
||||
// syncRequest
|
||||
// )
|
||||
}
|
||||
|
||||
fun cancelTask() {
|
||||
WorkManager.getInstance(App.get())
|
||||
.cancelUniqueWork(TASK_NAME)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.shuwei.intelligent.shelves.utils
|
||||
|
||||
/**
|
||||
* 命令常亮定义
|
||||
*/
|
||||
object Constant {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.shuwei.intelligent.shelves.utils
|
||||
|
||||
import java.text.SimpleDateFormat
|
||||
import java.time.LocalDateTime
|
||||
import java.time.ZoneId
|
||||
import java.time.format.DateTimeFormatter
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
|
||||
object DateTimeUtil {
|
||||
|
||||
const val YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"
|
||||
|
||||
fun formatDateTime(dateTime: Date, pattern: String = YYYY_MM_DD_HH_MM_SS): String {
|
||||
// val formatter = DateTimeFormatter.ofPattern(pattern)
|
||||
// return dateTime.format(formatter)
|
||||
val sdf = SimpleDateFormat(pattern, Locale.CHINA)
|
||||
return sdf.format(dateTime)
|
||||
}
|
||||
|
||||
// fun convert(dateStr: String, pattern: String = YYYY_MM_DD_HH_MM_SS): Date {
|
||||
// val formatter = DateTimeFormatter.ofPattern(pattern)
|
||||
// val ldt = LocalDateTime.parse(dateStr, formatter)
|
||||
// val zdt = ldt.atZone(ZoneId.systemDefault())
|
||||
// return Date.from(zdt.toInstant())
|
||||
// }
|
||||
//
|
||||
// fun main() {
|
||||
// val now = LocalDateTime.now()
|
||||
// println("默认格式: ${formatDateTime(now)}")
|
||||
// println("自定义格式: ${formatDateTime(now, "yyyy年MM月dd日 HH时mm分ss秒")}")
|
||||
// }
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.shuwei.intelligent.shelves.utils
|
||||
|
||||
fun decToHex(decimal: Int): String {
|
||||
if (decimal == 0) return "0"
|
||||
|
||||
val hexDigits = "0123456789ABCDEF"
|
||||
var num = decimal
|
||||
var result = ""
|
||||
|
||||
while (num > 0) {
|
||||
val remainder = num % 16
|
||||
result = hexDigits[remainder] + result
|
||||
num /= 16
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
fun hexToDec(hex: String): Int {
|
||||
val digits = "0123456789ABCDEF"
|
||||
var result = 0
|
||||
|
||||
hex.uppercase().forEach { char ->
|
||||
val digitValue = digits.indexOf(char)
|
||||
require(digitValue != -1) { "非法十六进制字符: $char" }
|
||||
result = result * 16 + digitValue
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.shuwei.intelligent.shelves.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.view.View
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
|
||||
|
||||
object KeyboardUtil {
|
||||
|
||||
fun hideKeyboard(context: Context, view: View) {
|
||||
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
|
||||
imm.hideSoftInputFromWindow(view.windowToken, 0)
|
||||
view.clearFocus() // 清除焦点避免键盘再次弹出
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//package com.shuwei.intelligent.shelves.utils
|
||||
//
|
||||
//
|
||||
//import android.serialport.*
|
||||
////import io.github.jeadyx.jserialport.SerialPort
|
||||
//import java.io.File
|
||||
//import java.io.IOException
|
||||
//import java.io.InputStream
|
||||
//import java.io.OutputStream
|
||||
//
|
||||
//class SerialPortHelper(
|
||||
// private val devicePath: String = "/dev/ttyS1",
|
||||
// private val baudRate: Int = 115200
|
||||
//) {
|
||||
// private var serialPort: SerialPort? = null
|
||||
// private var inputStream: InputStream? = null
|
||||
// private var outputStream: OutputStream? = null
|
||||
//
|
||||
// // 打开串口
|
||||
// fun open(): Boolean {
|
||||
// return try {
|
||||
// serialPort = SerialPort(File(devicePath), baudRate, 0)
|
||||
// inputStream = serialPort?.inputStream
|
||||
// outputStream = serialPort?.outputStream
|
||||
// true
|
||||
// } catch (e: IOException) {
|
||||
// false
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 发送数据
|
||||
// fun send(data: ByteArray): Boolean {
|
||||
// return try {
|
||||
// outputStream?.write(data)
|
||||
// outputStream?.flush()
|
||||
// true
|
||||
// } catch (e: IOException) {
|
||||
// false
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// // 接收数据(需在子线程调用)
|
||||
// fun receive(buffer: ByteArray): Int {
|
||||
// return inputStream?.read(buffer) ?: -1
|
||||
// }
|
||||
//
|
||||
// // 关闭串口
|
||||
// fun close() {
|
||||
// try {
|
||||
// inputStream?.close()
|
||||
// outputStream?.close()
|
||||
// serialPort?.close()
|
||||
// } catch (e: IOException) {
|
||||
// e.printStackTrace()
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.shuwei.intelligent.shelves.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.view.Gravity
|
||||
import android.view.LayoutInflater
|
||||
import android.view.View
|
||||
import android.widget.TextView
|
||||
import android.widget.Toast
|
||||
import com.shuwei.intelligent.shelves.R
|
||||
|
||||
|
||||
object ToastUtil {
|
||||
|
||||
fun show(context: Context, message: String, duration:Int = Toast.LENGTH_SHORT) {
|
||||
val inflater = LayoutInflater.from(context)
|
||||
val layout: View = inflater.inflate(R.layout.custom_toast, null)
|
||||
val textView = layout.findViewById<TextView>(R.id.tvMessage)
|
||||
textView.text = message
|
||||
|
||||
val toast = Toast(context)
|
||||
toast.view = layout // 设置自定义视图
|
||||
toast.setGravity(Gravity.CENTER, 0, 0) // 调整位置居中显示
|
||||
toast.setDuration(duration)
|
||||
toast.show()
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.shuwei.intelligent.shelves.utils
|
||||
|
||||
import android.widget.Toast
|
||||
import com.shuwei.intelligent.shelves.App
|
||||
|
||||
object UIUtils {
|
||||
fun toast(strRes: Int) {
|
||||
Toast.makeText(App.get(), strRes, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
|
||||
fun toast(str: String) {
|
||||
Toast.makeText(App.get(), str, Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package com.shuwei.intelligent.shelves.utils.ext
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.SharedPreferences
|
||||
import android.content.res.Resources
|
||||
import android.os.Bundle
|
||||
import android.util.TypedValue
|
||||
import android.view.View
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.EditText
|
||||
import android.widget.Toast
|
||||
import androidx.core.app.ActivityOptionsCompat
|
||||
import androidx.fragment.app.Fragment
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.reflect.TypeToken
|
||||
import com.shuwei.intelligent.shelves.utils.ToastUtil
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
fun Context.toast(
|
||||
message: String?,
|
||||
duration: Int = Toast.LENGTH_SHORT,
|
||||
) {
|
||||
if (message.isNullOrBlank()) {
|
||||
return
|
||||
}
|
||||
//Toast.makeText(this, message, duration).show()
|
||||
ToastUtil.show(this, message, duration)
|
||||
}
|
||||
|
||||
fun Fragment.toast(
|
||||
message: String?,
|
||||
duration: Int = 2000
|
||||
) {
|
||||
activity?.toast(message, duration)
|
||||
}
|
||||
|
||||
fun View.visible() {
|
||||
visibility = View.VISIBLE
|
||||
}
|
||||
|
||||
fun View.invisible() {
|
||||
visibility = View.INVISIBLE
|
||||
}
|
||||
|
||||
fun View.gone() {
|
||||
visibility = View.GONE
|
||||
}
|
||||
|
||||
inline fun <reified T : Activity> Context.startActivity(
|
||||
bundle: Bundle? = null,
|
||||
options: ActivityOptionsCompat? = null
|
||||
) {
|
||||
Intent(this, T::class.java).apply {
|
||||
bundle?.let { putExtras(it) }
|
||||
if (options != null && this@startActivity is Activity) {
|
||||
startActivity(this, options.toBundle())
|
||||
} else {
|
||||
startActivity(this)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <reified T> Context.startActivity(
|
||||
block: Intent.() -> Unit = {}
|
||||
) {
|
||||
Intent(this, T::class.java).apply {
|
||||
block()
|
||||
startActivity(this)
|
||||
}
|
||||
}
|
||||
|
||||
//inline fun <reified T : Activity> Context.startActivity(action:(bundle: Bundle)-> Unit) {
|
||||
// Intent(this, T::class.java).apply {
|
||||
// action(Bundle())
|
||||
// startActivity(this)
|
||||
// }
|
||||
//}
|
||||
|
||||
inline fun <reified T> String.toType(gson: Gson? = null, typeToken: TypeToken<T>): T {
|
||||
return (gson ?: Gson()).fromJson(this, typeToken.type)
|
||||
}
|
||||
|
||||
inline fun <reified T> String.toObject(gson: Gson? = null): T {
|
||||
return (gson ?: Gson()).fromJson(this, T::class.java)
|
||||
}
|
||||
|
||||
fun Any?.toJsonString(gson: Gson? = null): String {
|
||||
return (gson ?: Gson()).toJson(this) ?: ""
|
||||
}
|
||||
|
||||
@SuppressLint("ApplySharedPref")
|
||||
inline fun SharedPreferences.edit(
|
||||
commit: Boolean = false,
|
||||
action: SharedPreferences.Editor.() -> Unit
|
||||
) {
|
||||
val editor = edit()
|
||||
action(editor)
|
||||
if (commit) editor.commit() else editor.apply()
|
||||
}
|
||||
|
||||
fun SharedPreferences.put(vararg pairs: Pair<String, Any>) {
|
||||
edit {
|
||||
pairs.forEach { (key, value) ->
|
||||
when (value) {
|
||||
is Int -> putInt(key, value)
|
||||
is String -> putString(key, value)
|
||||
is Boolean -> putBoolean(key, value)
|
||||
is Float -> putFloat(key, value)
|
||||
is Long -> putLong(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val Float.dp: Float
|
||||
get() = TypedValue.applyDimension(
|
||||
TypedValue.COMPLEX_UNIT_DIP,
|
||||
this,
|
||||
Resources.getSystem().displayMetrics
|
||||
)
|
||||
|
||||
val Int.dp: Int
|
||||
get() = this.toFloat().dp.toInt()
|
||||
|
||||
fun EditText.addOnActionSearchListener(searchCallback: () -> Unit) {
|
||||
setOnEditorActionListener { v, actionId, event ->
|
||||
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
|
||||
// 处理搜索逻辑
|
||||
searchCallback()
|
||||
return@setOnEditorActionListener true // 阻止事件继续传递
|
||||
}
|
||||
return@setOnEditorActionListener false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun View.clickWithDebounce(delay: Long = 500, action: () -> Unit) {
|
||||
var job: Job? = null
|
||||
setOnClickListener {
|
||||
job?.cancel()
|
||||
job = CoroutineScope(Dispatchers.Main).launch {
|
||||
delay(delay)
|
||||
action()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.shuwei.intelligent.shelves.utils.ext
|
||||
|
||||
import android.graphics.Color
|
||||
import android.graphics.drawable.Drawable
|
||||
import android.graphics.drawable.GradientDrawable
|
||||
import androidx.core.graphics.toColorInt
|
||||
|
||||
interface DrawableDsl {
|
||||
fun shape(init: ShapeDsl.() -> Unit)
|
||||
}
|
||||
|
||||
interface ShapeDsl {
|
||||
fun solidColor(color: Int)
|
||||
fun stroke(width: Int, color: Int)
|
||||
fun cornerRadius(radius: Float)
|
||||
}
|
||||
|
||||
class DrawableBuilder : DrawableDsl {
|
||||
val drawables = mutableListOf<ShapeDrawable>()
|
||||
|
||||
override fun shape(init: ShapeDsl.() -> Unit) {
|
||||
val shape = ShapeDrawable()
|
||||
init(shape)
|
||||
drawables.add(shape)
|
||||
}
|
||||
}
|
||||
|
||||
class ShapeDrawable : ShapeDsl {
|
||||
var color: Int? = null
|
||||
var strokeWidth: Int? = null
|
||||
var strokeColor: Int? = null
|
||||
var cornerRadius: Float? = null
|
||||
|
||||
override fun solidColor(color: Int) {
|
||||
this.color = color
|
||||
}
|
||||
|
||||
override fun stroke(width: Int, color: Int) {
|
||||
this.strokeWidth = width
|
||||
this.strokeColor = color
|
||||
}
|
||||
|
||||
override fun cornerRadius(radius: Float) {
|
||||
this.cornerRadius = radius
|
||||
}
|
||||
}
|
||||
|
||||
fun createCustomDrawable(
|
||||
solidColor: String,
|
||||
strokeWidth: Int,
|
||||
strokeColor: String,
|
||||
radius: Int
|
||||
): Drawable {
|
||||
val builder = DrawableBuilder()
|
||||
builder.shape {
|
||||
solidColor(solidColor.toColorInt())
|
||||
stroke(strokeWidth, strokeColor.toColorInt())
|
||||
cornerRadius(radius.toFloat())
|
||||
}
|
||||
|
||||
return convertToDrawable(builder.drawables[0])
|
||||
}
|
||||
|
||||
fun convertToDrawable(shapeDrawable: ShapeDrawable): Drawable {
|
||||
val drawable = GradientDrawable()
|
||||
shapeDrawable.color?.let { drawable.setColor(it) }
|
||||
shapeDrawable.cornerRadius?.let { drawable.cornerRadius = it }
|
||||
shapeDrawable.strokeWidth?.let { drawable.setStroke(it, shapeDrawable.strokeColor ?: Color.BLACK) }
|
||||
return drawable
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.shuwei.intelligent.shelves.utils.ext
|
||||
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.text.Spanned
|
||||
|
||||
|
||||
inline fun buildSpannableString(builderAction: SpannableStringBuilder.() -> Unit): SpannableStringBuilder {
|
||||
return SpannableStringBuilder().apply(builderAction)
|
||||
}
|
||||
|
||||
fun SpannableStringBuilder.appendText(text: String, vararg spans: Any): SpannableStringBuilder {
|
||||
val start = length
|
||||
append(text)
|
||||
spans.forEach { span ->
|
||||
setSpan(span, start, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
fun SpannableStringBuilder.withSpan(span: Any, block: SpannableStringBuilder.() -> Unit) {
|
||||
val start = length
|
||||
block()
|
||||
setSpan(span, start, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//package com.shuwei.intelligent.shelves.viewmodel
|
||||
//
|
||||
//import androidx.lifecycle.LiveData
|
||||
//import androidx.lifecycle.MutableLiveData
|
||||
//import androidx.lifecycle.ViewModel
|
||||
//import com.shuwei.intelligent.shelves.model.ShelfModel
|
||||
//
|
||||
//class ShelfDataViewModel : ViewModel() {
|
||||
//
|
||||
// private val _shelfItems = MutableLiveData<MutableList<ShelfModel>>()
|
||||
// val shelfItems: LiveData<MutableList<ShelfModel>> = _shelfItems
|
||||
//
|
||||
// fun updateItems(newItems: MutableList<ShelfModel>) {
|
||||
// _shelfItems.value = newItems
|
||||
// }
|
||||
//
|
||||
// fun getCurrentItems(): MutableList<ShelfModel> = _shelfItems.value ?: mutableListOf()
|
||||
//
|
||||
//}
|
||||
Reference in New Issue
Block a user