path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Screen.kt | 1779852269 | package top.chengdongqing.weui.feature.hardware.screens
import android.app.Activity
import android.content.Context
import android.hardware.Sensor
import android.provider.Settings
import android.view.Window
import android.view.WindowManager
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.slider.WeSlider
import top.chengdongqing.weui.feature.hardware.utils.rememberSensorValue
@Composable
fun ScreenScreen() {
WeScreen(title = "Screen", description = "屏幕") {
val context = LocalContext.current
val window = (context as Activity).window
var screenBrightness by rememberScreenBrightness(window)
val lightBrightness = rememberSensorValue(Sensor.TYPE_LIGHT, true)
Box(modifier = Modifier.padding(horizontal = 12.dp)) {
WeSlider(
value = screenBrightness * 100,
onChange = {
screenBrightness = it / 100f
setScreenBrightness(window, screenBrightness)
}
)
}
Spacer(modifier = Modifier.height(20.dp))
Text(
text = "光线强度:${lightBrightness} Lux(勒克斯)",
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 10.sp
)
Spacer(modifier = Modifier.height(40.dp))
KeepScreenOn(window)
Spacer(modifier = Modifier.height(20.dp))
DisabledScreenshot(window)
}
}
@Composable
private fun KeepScreenOn(window: Window) {
var value by remember { mutableStateOf(false) }
WeButton(text = "${if (value) "取消" else "保持"}屏幕常亮") {
value = !value
if (value) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
}
}
@Composable
private fun DisabledScreenshot(window: Window) {
var value by remember { mutableStateOf(false) }
WeButton(
text = "${if (value) "取消" else "开启"}禁止截屏",
type = ButtonType.PLAIN
) {
value = !value
if (value) {
window.addFlags(WindowManager.LayoutParams.FLAG_SECURE)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
}
@Composable
private fun rememberScreenBrightness(window: Window): MutableState<Float> {
val context = LocalContext.current
val brightness = remember { mutableFloatStateOf(getScreenBrightness(context)) }
DisposableEffect(Unit) {
val initialValue = brightness.floatValue
onDispose {
setScreenBrightness(window, initialValue)
}
}
return brightness
}
private fun getScreenBrightness(context: Context): Float {
val brightness = Settings.System.getInt(
context.contentResolver,
Settings.System.SCREEN_BRIGHTNESS
)
return brightness / 255f * 2
}
private fun setScreenBrightness(window: Window, brightness: Float) {
window.attributes = window.attributes.apply {
screenBrightness = if (brightness > 1 || brightness < 0) -1f else brightness
}
}
|
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/WiFi.kt | 3365251655 | package top.chengdongqing.weui.feature.hardware.screens
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.os.Build
import android.provider.Settings
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.cardlist.cartList
import top.chengdongqing.weui.core.ui.components.divider.WeDivider
import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType
import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.utils.showToast
@SuppressLint("MissingPermission")
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun WiFiScreen() {
WeScreen(title = "Wi-Fi", description = "无线局域网", scrollEnabled = false) {
val context = LocalContext.current
val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager
var wifiList by remember { mutableStateOf<List<WiFiInfo>>(emptyList()) }
val permissionState = rememberMultiplePermissionsState(
remember {
listOf(
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_FINE_LOCATION
)
}
)
WeButton(text = "扫描Wi-Fi") {
if (permissionState.allPermissionsGranted) {
if (wifiManager == null) {
context.showToast("此设备不支持Wi-Fi")
} else if (wifiManager.isWifiEnabled) {
wifiList = buildWiFiList(wifiManager.scanResults)
} else {
context.showToast("Wi-Fi未开启")
context.startActivity(Intent(Settings.ACTION_WIFI_SETTINGS))
}
} else {
permissionState.launchMultiplePermissionRequest()
}
}
Spacer(modifier = Modifier.height(40.dp))
WiFiList(wifiList)
}
}
@Composable
private fun WiFiList(wifiList: List<WiFiInfo>) {
if (wifiList.isNotEmpty()) {
LazyColumn(modifier = Modifier.cartList()) {
itemsIndexed(wifiList) { index, wifi ->
WiFiListItem(wifi)
if (index < wifiList.lastIndex) {
WeDivider()
}
}
}
} else {
WeLoadMore(type = LoadMoreType.ALL_LOADED)
}
}
@Composable
private fun WiFiListItem(wifi: WiFiInfo) {
Row(
modifier = Modifier
.fillMaxWidth()
.height(60.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(text = wifi.name, color = MaterialTheme.colorScheme.onPrimary)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = wifi.band,
color = MaterialTheme.colorScheme.onSecondary,
fontSize = 10.sp,
modifier = Modifier
.border(0.5.dp, MaterialTheme.colorScheme.outline, RoundedCornerShape(3.dp))
.padding(horizontal = 3.dp)
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
if (wifi.secure) {
Icon(
imageVector = Icons.Filled.Lock,
contentDescription = "加密",
modifier = Modifier.size(20.dp),
tint = MaterialTheme.colorScheme.onSecondary
)
}
Spacer(modifier = Modifier.width(8.dp))
Text(
text = wifi.level,
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 14.sp
)
}
}
}
private fun buildWiFiList(scanResultList: List<ScanResult>): List<WiFiInfo> {
return scanResultList.sortedByDescending { it.level }
.map { item ->
WiFiInfo(
name = getSSID(item),
band = determineWifiBand(item.frequency),
level = "${calculateSignalLevel(item.level)}%",
secure = isWifiSecure(item.capabilities)
)
}
}
private fun getSSID(wifi: ScanResult): String {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
wifi.wifiSsid?.bytes?.decodeToString() ?: ""
} else {
@Suppress("DEPRECATION")
wifi.SSID
}
}
private fun determineWifiBand(frequency: Int): String {
return when (frequency) {
in 2400..2500 -> "2.4G"
in 4900..5900 -> "5G"
in 5925..7125 -> "6G"
else -> "未知频段"
}
}
private fun calculateSignalLevel(rssi: Int, numLevels: Int = 100): Int {
val minRssi = -100
val maxRssi = -55
if (rssi <= minRssi) {
return 0
} else if (rssi >= maxRssi) {
return numLevels - 1
} else {
val inputRange = (maxRssi - minRssi).toFloat()
val outputRange = (numLevels - 1).toFloat()
return ((rssi - minRssi).toFloat() * outputRange / inputRange).toInt()
}
}
private fun isWifiSecure(capabilities: String): Boolean {
return capabilities.contains("WEP") || capabilities.contains("PSK") || capabilities.contains("EAP")
}
private data class WiFiInfo(
val name: String,
val band: String,
val level: String,
val secure: Boolean
) |
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Gyroscope.kt | 4017728490 | package top.chengdongqing.weui.feature.hardware.screens
import android.hardware.Sensor
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem
import top.chengdongqing.weui.core.ui.components.cardlist.cartList
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.utils.format
import top.chengdongqing.weui.feature.hardware.utils.rememberSensorValues
@Composable
fun GyroscopeScreen() {
WeScreen(title = "Gyroscope", description = "陀螺仪,用于测量旋转运动", scrollEnabled = false) {
val (observing, setObserving) = remember { mutableStateOf(false) }
val values = rememberSensorValues(Sensor.TYPE_GYROSCOPE, observing)
if (!observing) {
WeButton(text = "开始监听") {
setObserving(true)
}
} else {
WeButton(text = "取消监听", type = ButtonType.PLAIN) {
setObserving(false)
}
}
Spacer(modifier = Modifier.height(40.dp))
values?.let {
Text(
text = "单位:rad/s(弧度/秒)",
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 10.sp
)
Spacer(modifier = Modifier.height(20.dp))
LazyColumn(modifier = Modifier.cartList()) {
itemsIndexed(it) { index, value ->
WeCardListItem(
label = "${getAxisLabel(index)}轴",
value = value.format()
)
}
}
}
}
}
private fun getAxisLabel(index: Int): String {
return when (index) {
0 -> "X"
1 -> "Y"
2 -> "Z"
else -> ""
}
} |
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/screens/Fingerprint.kt | 2973550628 | package top.chengdongqing.weui.feature.hardware.screens
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG
import androidx.biometric.BiometricPrompt
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.fragment.app.FragmentActivity
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.utils.showToast
@Composable
fun FingerprintScreen() {
WeScreen(title = "Fingerprint", description = "指纹认证") {
val context = LocalContext.current
WeButton(text = "指纹认证") {
context.startActivity(BiometricActivity.newIntent(context))
}
}
}
class BiometricActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("指纹认证")
.setAllowedAuthenticators(BIOMETRIC_STRONG)
.setNegativeButtonText("取消认证")
.build()
createBiometricPrompt(this).authenticate(promptInfo)
}
companion object {
fun newIntent(context: Context) = Intent(context, BiometricActivity::class.java)
}
}
private fun createBiometricPrompt(activity: FragmentActivity): BiometricPrompt {
val callback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
activity.finish()
activity.showToast(errString.toString())
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
activity.showToast("认证失败")
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
activity.setResult(Activity.RESULT_OK)
activity.finish()
activity.showToast("认证成功")
}
}
return BiometricPrompt(activity, callback)
}
// 使用旧API可以自定义界面样式,但安全性和兼容性需要自己控制
//class FingerprintViewModel(private val application: Application) : AndroidViewModel(application) {
//
// private lateinit var fingerprintManager: FingerprintManager
// private lateinit var cancellationSignal: CancellationSignal
//
// fun initFingerprintManager(context: Context) {
// fingerprintManager =
// context.getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager
// startListening(null)
// }
//
// private fun startListening(cryptoObject: FingerprintManager.CryptoObject?) {
// cancellationSignal = CancellationSignal()
// if (ActivityCompat.checkSelfPermission(
// application,
// Manifest.permission.USE_FINGERPRINT
// ) != PackageManager.PERMISSION_GRANTED
// ) {
// return
// }
// fingerprintManager.authenticate(
// cryptoObject,
// cancellationSignal,
// 0,
// authenticationCallback,
// null
// )
// }
//
// private val authenticationCallback = object : FingerprintManager.AuthenticationCallback() {
// override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
// super.onAuthenticationError(errorCode, errString)
// // 处理错误情况
// application.showToast("出现错误")
// }
//
// override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult) {
// super.onAuthenticationSucceeded(result)
// // 认证成功
// application.showToast("认证成功")
// }
//
// override fun onAuthenticationFailed() {
// super.onAuthenticationFailed()
// // 认证失败
// application.showToast("认证失败")
// }
// }
//
// fun cancelAuthentication() {
// cancellationSignal.cancel()
// }
//} |
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/compass/Compass.kt | 3397295832 | package top.chengdongqing.weui.feature.hardware.compass
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorManager
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import top.chengdongqing.weui.core.utils.UpdatedEffect
import top.chengdongqing.weui.core.utils.formatDegree
import top.chengdongqing.weui.core.utils.polarToCartesian
import top.chengdongqing.weui.core.utils.vibrateShort
@Composable
fun WeCompass(compassViewModel: CompassViewModel = viewModel()) {
val context = LocalContext.current
val degrees = compassViewModel.degrees
val sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) // 加速度计
val magnetometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) // 磁力计
LaunchedEffect(compassViewModel.observing) {
if (compassViewModel.observing) {
sensorManager.registerListener(
compassViewModel.eventListener,
accelerometerSensor,
SensorManager.SENSOR_DELAY_UI
)
sensorManager.registerListener(
compassViewModel.eventListener,
magnetometerSensor,
SensorManager.SENSOR_DELAY_UI
)
} else {
sensorManager.unregisterListener(compassViewModel.eventListener)
}
}
DisposableEffect(Unit) {
onDispose {
sensorManager.unregisterListener(compassViewModel.eventListener)
}
}
// 指向准点方位后触发震动
UpdatedEffect(degrees) {
if (degrees % 90 == 0) {
context.vibrateShort()
}
}
CompassSurface(degrees)
}
@Composable
private fun CompassSurface(degrees: Int) {
val textMeasurer = rememberTextMeasurer()
val colors = MaterialTheme.compassColorScheme
Canvas(
modifier = Modifier
.size(300.dp)
.fillMaxSize()
) {
val center = Offset(size.width / 2, size.height / 2)
val radius = size.minDimension / 2
drawCompassFace(center, radius, colors)
drawCompassScales(center, radius, degrees, textMeasurer, colors)
drawNorthIndicator(radius, colors.indicatorColor)
drawCurrentDegrees(radius, degrees, textMeasurer, colors)
}
}
// 绘制圆盘
private fun DrawScope.drawCompassFace(center: Offset, radius: Float, colors: CompassColors) {
drawCircle(
color = colors.containerColor,
center = center,
radius = radius
)
}
// 绘制罗盘的刻度和方位
private fun DrawScope.drawCompassScales(
center: Offset,
radius: Float,
degrees: Int,
textMeasurer: TextMeasurer,
colors: CompassColors
) {
for (angle in 0 until 360 step 10) {
val angleRadians = Math.toRadians(angle.toDouble() - degrees - 90)
drawScaleLine(center, radius, angle, angleRadians, colors)
drawDegreeText(center, radius, angle, angleRadians, textMeasurer, colors)
drawCardinalPoint(center, radius, angle, angleRadians, textMeasurer, colors)
}
}
// 绘制刻度线
private fun DrawScope.drawScaleLine(
center: Offset,
radius: Float,
angle: Int,
angleRadians: Double,
colors: CompassColors
) {
val localRadius = radius - 8.dp.toPx()
val startRadius = if (angle % 45 == 0) {
localRadius - 10.dp.toPx()
} else {
localRadius - 8.dp.toPx()
}
val (startX, startY) = polarToCartesian(center, startRadius, angleRadians)
val (endX, endY) = polarToCartesian(center, localRadius, angleRadians)
drawLine(
color = if (angle % 45 == 0) colors.scalePrimaryColor else colors.scaleSecondaryColor,
start = Offset(startX, startY),
end = Offset(endX, endY),
strokeWidth = 1.dp.toPx()
)
}
// 绘制度数刻度
private fun DrawScope.drawDegreeText(
center: Offset,
radius: Float,
angle: Int,
angleRadians: Double,
textMeasurer: TextMeasurer,
colors: CompassColors
) {
if (angle % 30 == 0) {
val degreeText = AnnotatedString(
angle.toString(),
SpanStyle(fontSize = 12.sp)
)
val textRadius = radius - 8.dp.toPx() - 26.dp.toPx()
val (degreeX, degreeY) = polarToCartesian(center, textRadius, angleRadians)
val textLayoutResult = textMeasurer.measure(degreeText)
drawText(
textLayoutResult,
color = if (angle % 90 == 0) colors.scalePrimaryColor else colors.scaleSecondaryColor,
topLeft = Offset(
degreeX - textLayoutResult.size.width / 2,
degreeY - textLayoutResult.size.height / 2
)
)
}
}
// 绘制方位文本
private fun DrawScope.drawCardinalPoint(
center: Offset,
radius: Float,
angle: Int,
angleRadians: Double,
textMeasurer: TextMeasurer,
colors: CompassColors
) {
if (angle % 90 == 0) {
val cardinalPoint = getCardinalPoint(angle)
val textRadius = radius - 8.dp.toPx() - 60.dp.toPx()
val (textX, textY) = polarToCartesian(center, textRadius, angleRadians)
val text = AnnotatedString(
cardinalPoint,
SpanStyle(fontSize = 20.sp, fontWeight = FontWeight.Bold)
)
val textLayoutResult = textMeasurer.measure(text)
drawText(
textLayoutResult,
color = colors.fontColor,
topLeft = Offset(
textX - textLayoutResult.size.width / 2,
textY - textLayoutResult.size.height / 2
)
)
}
}
// 绘制向北指针
private fun DrawScope.drawNorthIndicator(radius: Float, color: Color) {
drawLine(
color,
Offset(x = radius, y = -8.dp.toPx()),
Offset(x = radius, y = 18.dp.toPx()),
strokeWidth = 3.dp.toPx(),
cap = StrokeCap.Round
)
}
// 绘制当前度数
private fun DrawScope.drawCurrentDegrees(
radius: Float,
degrees: Int,
textMeasurer: TextMeasurer,
colors: CompassColors
) {
val degreeText = AnnotatedString(
formatDegree(degrees.toFloat(), 0),
SpanStyle(fontSize = 40.sp, fontWeight = FontWeight.Bold)
)
val textLayoutResult = textMeasurer.measure(degreeText)
drawText(
textLayoutResult,
color = colors.fontColor,
topLeft = Offset(
radius - textLayoutResult.size.width / 2,
radius - textLayoutResult.size.height / 2
)
)
}
// 获取方位名称
private fun getCardinalPoint(angle: Int): String {
return when (angle) {
0 -> "北"
90 -> "东"
180 -> "南"
270 -> "西"
else -> ""
}
}
private data class CompassColors(
val containerColor: Color,
val fontColor: Color,
val scalePrimaryColor: Color,
val scaleSecondaryColor: Color,
val indicatorColor: Color
)
private val MaterialTheme.compassColorScheme: CompassColors
@Composable
get() = CompassColors(
containerColor = colorScheme.onBackground,
fontColor = colorScheme.onPrimary,
scalePrimaryColor = colorScheme.onSecondary,
scaleSecondaryColor = colorScheme.outline,
indicatorColor = colorScheme.primary
) |
WeUI/feature/hardware/src/main/kotlin/top/chengdongqing/weui/feature/hardware/compass/CompassViewModel.kt | 2897692147 | package top.chengdongqing.weui.feature.hardware.compass
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
class CompassViewModel : ViewModel() {
var degrees by mutableIntStateOf(0)
private set
var accuracy by mutableStateOf<Int?>(null)
private set
var observing by mutableStateOf(false)
val eventListener by lazy {
CompassEventListener(
onDegreesChange = {
degrees = it
},
onAccuracyChange = {
accuracy = it
}
)
}
}
class CompassEventListener(
val onDegreesChange: (Int) -> Unit,
val onAccuracyChange: (Int) -> Unit
) : SensorEventListener {
private var gravity: FloatArray? = null
private var geomagnetic: FloatArray? = null
override fun onSensorChanged(event: SensorEvent) {
when (event.sensor.type) {
Sensor.TYPE_ACCELEROMETER -> gravity = event.values.clone()
Sensor.TYPE_MAGNETIC_FIELD -> geomagnetic = event.values.clone()
}
if (gravity != null && geomagnetic != null) {
val r = FloatArray(9)
val i = FloatArray(9)
val success = SensorManager.getRotationMatrix(r, i, gravity, geomagnetic)
if (success) {
val orientation = FloatArray(3)
SensorManager.getOrientation(r, orientation)
var azimuth = Math.toDegrees(orientation.first().toDouble())
if (azimuth < 0) {
azimuth += 360
}
onDegreesChange(azimuth.toInt())
}
}
}
override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {
if (sensor.type == Sensor.TYPE_MAGNETIC_FIELD) {
onAccuracyChange(accuracy)
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/LocationPickerActivity.kt | 2225824964 | package top.chengdongqing.weui.feature.location.picker
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import top.chengdongqing.weui.core.ui.theme.WeUITheme
import top.chengdongqing.weui.feature.location.data.model.LocationItem
class LocationPickerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WeUITheme {
WeLocationPicker(onCancel = { finish() }) { location ->
val intent = Intent().apply {
putExtra("location", location)
}
setResult(RESULT_OK, intent)
finish()
}
}
}
}
companion object {
fun newIntent(context: Context) = Intent(context, LocationPickerActivity::class.java)
}
}
@Composable
fun rememberPickLocationLauncher(onChange: (LocationItem) -> Unit): () -> Unit {
val context = LocalContext.current
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
result.data?.apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
getParcelableExtra("location", LocationItem::class.java)?.let(onChange)
} else {
@Suppress("DEPRECATION")
(getParcelableExtra("location") as? LocationItem)?.let(onChange)
}
}
}
}
return {
launcher.launch(LocationPickerActivity.newIntent(context))
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/locationlist/SearchableLocationList.kt | 1915418465 | package top.chengdongqing.weui.feature.location.picker.locationlist
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.KeyboardArrowDown
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.unit.dp
import com.amap.api.maps.CameraUpdateFactory
import top.chengdongqing.weui.core.ui.components.searchbar.WeSearchBar
import top.chengdongqing.weui.feature.location.picker.LocationPickerState
@Composable
fun SearchableLocationList(state: LocationPickerState, listState: LazyListState) {
val animatedHeightFraction = animateFloatAsState(
targetValue = if (state.isListExpanded) 0.7f else 0.4f,
label = "LocationListHeightAnimation"
)
val nestedScrollConnection = remember(state) {
LocationListNestedScrollConnection(
state,
animatedHeightFraction
)
}
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(animatedHeightFraction.value)
.expandedStyle(state.isListExpanded)
.background(MaterialTheme.colorScheme.surface)
.nestedScroll(nestedScrollConnection)
) {
if (state.isListExpanded) {
TopArrow(state)
}
if (state.isSearchMode) {
SearchPanel(state)
} else {
SearchInput(state)
LocationList(
listState,
state.paging,
state.selectedIndex,
onSelect = {
// 保存选择的位置索引
state.selectedIndex = it
// 移动地图中心点到选中的位置
val latLng = state.paging.dataList[it].latLng
state.map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f))
}
) {
if (!state.paging.isAllLoaded && !state.paging.isLoading) {
val pageNum = state.paging.startLoadMore()
state.search(state.mapCenterLatLng, pageNum = pageNum)
.apply {
val filteredList = this.filter { item ->
state.paging.dataList.none { it.name == item.name }
}
state.paging.endLoadMore(filteredList)
}
}
}
}
}
}
@Composable
private fun ColumnScope.TopArrow(state: LocationPickerState) {
Box(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = 16.dp)
.clip(RoundedCornerShape(20.dp))
.background(MaterialTheme.colorScheme.background)
.clickable { state.isListExpanded = false }
.padding(horizontal = 12.dp)
) {
Icon(
imageVector = Icons.Outlined.KeyboardArrowDown,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSecondary,
modifier = Modifier.size(22.dp)
)
}
}
private fun Modifier.expandedStyle(expanded: Boolean) = if (expanded) {
this
.offset(y = (-12).dp)
.clip(RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp))
} else {
this
}
@Composable
private fun SearchInput(state: LocationPickerState) {
WeSearchBar(
value = "",
modifier = Modifier.padding(16.dp),
placeholder = "搜索地点",
disabled = true,
onClick = {
state.isSearchMode = true
}
) {}
}
private class LocationListNestedScrollConnection(
private val state: LocationPickerState,
private val heightFraction: State<Float>,
) : NestedScrollConnection {
override fun onPreScroll(
available: Offset,
source: NestedScrollSource
): Offset {
if (available.y < 0 && !state.isListExpanded) {
state.isListExpanded = true
}
return if (heightFraction.value == 0.7f) Offset.Zero else available
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
if (available.y > 0 && state.isListExpanded) {
state.isListExpanded = false
}
return Offset.Zero
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/locationlist/SearchPanel.kt | 3303294761 | package top.chengdongqing.weui.feature.location.picker.locationlist
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.unit.dp
import com.amap.api.maps.CameraUpdateFactory
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.filter
import top.chengdongqing.weui.core.ui.components.searchbar.WeSearchBar
import top.chengdongqing.weui.core.utils.UpdatedEffect
import top.chengdongqing.weui.core.utils.clickableWithoutRipple
import top.chengdongqing.weui.core.utils.rememberKeyboardHeight
import top.chengdongqing.weui.feature.location.data.model.LocationItem
import top.chengdongqing.weui.feature.location.picker.LocationPickerState
@Composable
fun SearchPanel(state: LocationPickerState) {
val listState = rememberLazyListState()
val paging = state.pagingOfSearch
val keywordFlow = remember { MutableStateFlow("") }
val keyword by keywordFlow.collectAsState()
var type by remember { mutableIntStateOf(0) }
SearchingEffect(keywordFlow, state, paging, listState, keyword, type)
KeyboardEffect(state)
Column {
WeSearchBar(
value = keyword,
modifier = Modifier.padding(16.dp),
focused = true,
onFocusChange = {
if (!it) {
state.isSearchMode = false
}
}
) {
keywordFlow.value = it
}
TypeTabRow(type) { type = it }
LocationList(
listState,
paging,
state.selectedIndexOfSearch,
onSelect = {
// 保存选择的位置索引
state.selectedIndexOfSearch = it
// 移动地图中心点到选中的位置
val latLng = paging.dataList[it].latLng
state.map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f))
// 选择位置后展开地图
state.isListExpanded = false
}
) {
if (!paging.isAllLoaded && !state.paging.isLoading) {
val pageNum = paging.startLoadMore()
state.search(
location = if (type == 0) state.currentLatLng else null,
keyword = keyword,
pageNum = pageNum
).apply {
val filteredList = this.filter { item ->
paging.dataList.none { it.name == item.name }
}
paging.endLoadMore(filteredList)
}
}
}
}
}
@Composable
private fun TypeTabRow(type: Int, onChange: (Int) -> Unit) {
val options = remember { listOf("附近", "不限") }
var itemWidth by remember { mutableStateOf(0.dp) }
val density = LocalDensity.current
Column(modifier = Modifier.padding(horizontal = 16.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
options.forEachIndexed { index, item ->
val active = index == type
Text(
text = item,
color = if (active) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.onPrimary
},
modifier = Modifier
.onSizeChanged {
itemWidth = with(density) { it.width.toDp() }
}
.clickableWithoutRipple {
onChange(index)
}
.padding(vertical = 3.dp)
)
}
}
val animatedOffsetX by animateDpAsState(
(type * itemWidth.value + type * 16).dp,
label = ""
)
HorizontalDivider(
modifier = Modifier
.width(itemWidth)
.offset(x = animatedOffsetX),
thickness = 2.dp,
color = MaterialTheme.colorScheme.primary
)
Spacer(modifier = Modifier.height(16.dp))
}
}
@OptIn(FlowPreview::class)
@Composable
private fun SearchingEffect(
keywordFlow: Flow<String>,
state: LocationPickerState,
paging: PagingState<LocationItem>,
listState: LazyListState,
keyword: String,
type: Int
) {
val currentKeyword by rememberUpdatedState(newValue = keyword)
val currentType by rememberUpdatedState(newValue = type)
LaunchedEffect(keywordFlow) {
keywordFlow
.debounce(300)
.filter { it.isNotBlank() }
.collect {
refresh(state, paging, listState, it, currentType)
}
}
UpdatedEffect(currentType) {
refresh(state, paging, listState, currentKeyword, currentType)
}
}
private suspend fun refresh(
state: LocationPickerState,
paging: PagingState<LocationItem>,
listState: LazyListState,
keyword: String,
type: Int
) {
state.selectedIndexOfSearch = null
if (keyword.isNotBlank()) {
paging.startRefresh()
state.search(
location = if (type == 0) state.currentLatLng else null,
keyword = keyword
).apply {
paging.endRefresh(this)
}
listState.scrollToItem(0)
} else {
paging.dataList = emptyList()
}
}
@Composable
private fun KeyboardEffect(state: LocationPickerState) {
val keyboardController = LocalSoftwareKeyboardController.current
val keyboardHeight = rememberKeyboardHeight()
UpdatedEffect(keyboardHeight) {
if (keyboardHeight > 0.dp) {
state.isListExpanded = true
}
}
UpdatedEffect(state.isListExpanded) {
if (!state.isListExpanded) {
keyboardController?.hide()
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/locationlist/LocationList.kt | 1124898938 | package top.chengdongqing.weui.feature.location.picker.locationlist
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import top.chengdongqing.weui.core.ui.components.R
import top.chengdongqing.weui.core.ui.components.divider.WeDivider
import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType
import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore
import top.chengdongqing.weui.core.ui.components.loading.WeLoading
import top.chengdongqing.weui.core.ui.components.refreshview.rememberLoadMoreState
import top.chengdongqing.weui.core.utils.clickableWithoutRipple
import top.chengdongqing.weui.core.utils.formatDistance
import top.chengdongqing.weui.feature.location.data.model.LocationItem
@Composable
fun LocationList(
listState: LazyListState,
pagingState: PagingState<LocationItem>,
selectedIndex: Int?,
onSelect: (Int) -> Unit,
onLoadMore: suspend () -> Unit
) {
val loadMoreState = rememberLoadMoreState(
enabled = { !pagingState.isAllLoaded },
onLoadMore
)
Box(modifier = Modifier.nestedScroll(loadMoreState.nestedScrollConnection)) {
LazyColumn(state = listState, contentPadding = PaddingValues(bottom = 16.dp)) {
itemsIndexed(
pagingState.dataList,
key = { _, item -> item.id ?: item.name }
) { index, item ->
LocationListItem(index == selectedIndex, item) {
onSelect(index)
}
if (index < pagingState.dataList.lastIndex) {
WeDivider()
}
}
item {
if (loadMoreState.isLoadingMore) {
WeLoadMore(listState = listState)
} else if (pagingState.isAllLoaded) {
WeLoadMore(type = LoadMoreType.ALL_LOADED)
}
}
}
if (pagingState.isLoading && !loadMoreState.isLoadingMore) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(top = 80.dp),
contentAlignment = Alignment.Center
) {
WeLoading(size = 80.dp)
}
}
}
}
@Composable
private fun LocationListItem(checked: Boolean, location: LocationItem, onClick: () -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickableWithoutRipple { onClick() }
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = location.name,
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 17.sp
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = buildList {
location.distance?.let { add(formatDistance(it)) }
location.address?.let { add(it) }
}.joinToString(" | "),
color = MaterialTheme.colorScheme.onSecondary,
fontSize = 14.sp
)
}
if (checked) {
Icon(
painter = painterResource(id = R.drawable.ic_check),
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/locationlist/PagingState.kt | 938845446 | package top.chengdongqing.weui.feature.location.picker.locationlist
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
@Stable
interface PagingState<T> {
var dataList: List<T>
val pageNumber: Int
val pageSize: Int
val isLoading: Boolean
val isAllLoaded: Boolean
fun startRefresh()
fun endRefresh(dataList: List<T>)
fun startLoadMore(): Int
fun endLoadMore(dataList: List<T>)
}
class PagingStateImpl<T>(
override val pageSize: Int = 10,
initialLoading: Boolean = false
) : PagingState<T> {
override var dataList by mutableStateOf<List<T>>(emptyList())
override var pageNumber by mutableIntStateOf(1)
override var isLoading by mutableStateOf(initialLoading)
override var isAllLoaded by mutableStateOf(false)
override fun startRefresh() {
isLoading = true
pageNumber = 1
}
override fun endRefresh(dataList: List<T>) {
this.dataList = dataList
isAllLoaded = dataList.size < pageSize
if (!isAllLoaded) {
pageNumber++
}
isLoading = false
}
override fun startLoadMore(): Int {
isLoading = true
return pageNumber
}
override fun endLoadMore(dataList: List<T>) {
this.dataList += dataList.also {
if (it.isNotEmpty()) {
pageNumber++
}
isAllLoaded = it.size < pageSize
}
isLoading = false
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/LocationPickerState.kt | 330641194 | package top.chengdongqing.weui.feature.location.picker
import android.view.MotionEvent
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.LatLng
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import top.chengdongqing.weui.feature.location.data.model.LocationItem
import top.chengdongqing.weui.feature.location.data.repository.LocationRepository
import top.chengdongqing.weui.feature.location.data.repository.LocationRepositoryImpl
import top.chengdongqing.weui.feature.location.picker.locationlist.PagingState
import top.chengdongqing.weui.feature.location.picker.locationlist.PagingStateImpl
import top.chengdongqing.weui.feature.location.utils.isLoaded
import top.chengdongqing.weui.feature.location.utils.toLatLng
@Stable
interface LocationPickerState {
/**
* 地图实例
*/
val map: AMap
/**
* 当前设备坐标
*/
val currentLatLng: LatLng?
/**
* 地图中心点坐标
*/
var mapCenterLatLng: LatLng?
/**
* 是否是搜索模式
*/
var isSearchMode: Boolean
/**
* 是否展开列表
*/
var isListExpanded: Boolean
/**
* 分页信息
*/
val paging: PagingState<LocationItem>
/**
* 选中的位置索引
*/
var selectedIndex: Int
/**
* 搜索模式下的分页信息
*/
val pagingOfSearch: PagingState<LocationItem>
/**
* 搜索模式下选中的位置索引
*/
var selectedIndexOfSearch: Int?
/**
* 当前选中的位置信息
*/
val selectedLocation: LocationItem?
/**
* 搜索位置
*/
suspend fun search(
location: LatLng?,
keyword: String = "",
pageNum: Int = 1,
pageSize: Int = 10
): List<LocationItem>
}
@Composable
fun rememberLocationPickerState(map: AMap, listState: LazyListState): LocationPickerState {
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val locationRepository = remember { LocationRepositoryImpl(context) }
val currentLocation = locationRepository.currentLocation.collectAsState(initial = null)
val state = remember {
LocationPickerStateImpl(
map,
locationRepository,
coroutineScope,
currentLocation,
listState
)
}
// 恢复上次缓存的位置信息
LaunchedEffect(currentLocation.value) {
currentLocation.value?.let {
if (state.mapCenterLatLng == null) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(it, 16f))
state.mapCenterLatLng = it
}
}
}
return state
}
private class LocationPickerStateImpl(
override val map: AMap,
private val locationRepository: LocationRepository,
private val coroutineScope: CoroutineScope,
private val _currentLatLng: State<LatLng?>,
private val listState: LazyListState
) : LocationPickerState {
override var currentLatLng: LatLng?
get() = _currentLatLng.value
set(value) {
value?.let {
coroutineScope.launch {
// 缓存到datastore,方便再次进入时快速获取定位
locationRepository.saveCurrentLocation(it)
}
}
}
override var mapCenterLatLng: LatLng?
get() = _mapCenterLatLng
set(value) {
_mapCenterLatLng = value
// 退出搜索模式
if (isSearchMode) {
isSearchMode = false
}
if (value != null) {
// 重置选中项
selectedIndex = 0
// 准备刷新
paging.startRefresh()
coroutineScope.launch {
// 获取地图中心点的位置信息,转为列表是方便和之后附近的位置列表合并
val centerLocationList = locationToAddress(value)?.let { listOf(it) }
?: emptyList()
// 搜索附近位置信息
search(value).apply {
paging.endRefresh(centerLocationList + this)
}
// 滚动到第一项
listState.scrollToItem(0)
}
}
}
override var isSearchMode: Boolean
get() = _isSearchMode
set(value) {
_isSearchMode = value
isListExpanded = value
if (!value) {
// 重置搜索结果
pagingOfSearch.dataList = emptyList()
// 恢复地图视野
mapCenterLatLng?.let {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(it, 16f))
}
}
}
override var isListExpanded by mutableStateOf(false)
override val paging = PagingStateImpl<LocationItem>(initialLoading = true)
override var selectedIndex by mutableIntStateOf(0)
override val pagingOfSearch = PagingStateImpl<LocationItem>()
override var selectedIndexOfSearch by mutableStateOf<Int?>(null)
override val selectedLocation: LocationItem?
get() {
return if (!isSearchMode) {
paging.dataList.getOrNull(selectedIndex)
} else {
selectedIndexOfSearch?.let { pagingOfSearch.dataList.getOrNull(it) }
}
}
private var _mapCenterLatLng by mutableStateOf<LatLng?>(null)
private var _isSearchMode by mutableStateOf(false)
override suspend fun search(
location: LatLng?,
keyword: String,
pageNum: Int,
pageSize: Int
): List<LocationItem> {
if (location == null && keyword.isBlank()) {
return emptyList()
}
return locationRepository.search(
location,
keyword,
pageNum,
pageSize,
currentLatLng
)
}
init {
setMapClickAndDragListener()
setLocationChangeListener()
}
private suspend fun locationToAddress(latLng: LatLng): LocationItem? {
return locationRepository.locationToAddress(latLng)?.let {
val address = it.formatAddress
val startIndex = address.lastIndexOf(it.district)
val name = address.slice(startIndex..address.lastIndex)
LocationItem(
name = name,
address = address,
latLng = latLng
)
}
}
// 监听地图点击或拖拽事件
private fun setMapClickAndDragListener() {
map.setOnMapClickListener {
map.animateCamera(CameraUpdateFactory.newLatLng(it))
mapCenterLatLng = it
}
map.setOnPOIClickListener {
map.animateCamera(CameraUpdateFactory.newLatLng(it.coordinate))
mapCenterLatLng = it.coordinate
}
map.setOnMapTouchListener {
if (it.action == MotionEvent.ACTION_UP && !isSearchMode) {
mapCenterLatLng = map.cameraPosition.target
}
}
}
// 监听当前位置变化
private fun setLocationChangeListener() {
map.setOnMyLocationChangeListener { location ->
if (location.isLoaded()) {
location.toLatLng().let {
// 只有在当前位置为空且非搜索模式时才将地图视野移至当前位置
if (currentLatLng == null && !isSearchMode) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(it, 16f))
mapCenterLatLng = it
}
currentLatLng = it
}
}
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/picker/LocationPicker.kt | 2771929141 | package top.chengdongqing.weui.feature.location.picker
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.TweenSpec
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBarsPadding
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.amap.api.maps.model.MarkerOptions
import top.chengdongqing.weui.core.ui.components.R
import top.chengdongqing.weui.core.ui.components.button.ButtonSize
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.utils.clickableWithoutRipple
import top.chengdongqing.weui.feature.location.AMap
import top.chengdongqing.weui.feature.location.LocationControl
import top.chengdongqing.weui.feature.location.data.model.LocationItem
import top.chengdongqing.weui.feature.location.picker.locationlist.SearchableLocationList
import top.chengdongqing.weui.feature.location.rememberAMapState
import top.chengdongqing.weui.feature.location.utils.createBitmapDescriptor
@Composable
fun WeLocationPicker(
onCancel: () -> Unit,
onConfirm: (LocationItem) -> Unit
) {
val mapState = rememberAMapState()
val listState = rememberLazyListState()
val state = rememberLocationPickerState(mapState.map, listState)
Column(modifier = Modifier.fillMaxSize()) {
Box(modifier = Modifier.weight(1f)) {
AMap(state = mapState) { map ->
LocationControl(map) {
state.mapCenterLatLng = it
}
}
TopBar(
hasSelected = state.selectedLocation != null,
onCancel
) {
onConfirm(state.selectedLocation!!)
}
LocationMarker(state)
}
Box(modifier = Modifier.background(MaterialTheme.colorScheme.surface)) {
SearchableLocationList(state, listState)
}
}
}
@Composable
private fun BoxScope.LocationMarker(state: LocationPickerState) {
if (!state.isSearchMode) {
val offsetY = remember { Animatable(0f) }
val animationSpec = remember { TweenSpec<Float>(durationMillis = 300) }
LaunchedEffect(state.mapCenterLatLng) {
offsetY.animateTo(-10f, animationSpec)
offsetY.animateTo(0f, animationSpec)
}
Image(
painter = painterResource(id = R.drawable.ic_location_marker),
contentDescription = null,
modifier = Modifier
.align(Alignment.Center)
.size(50.dp)
.offset(y = (-25).dp + offsetY.value.dp)
)
} else if (state.selectedLocation != null) {
val context = LocalContext.current
DisposableEffect(state.selectedLocation) {
val markerOptions = MarkerOptions().apply {
position(state.selectedLocation?.latLng)
icon(
createBitmapDescriptor(
context,
R.drawable.ic_location_marker,
160,
160
)
)
}
val marker = state.map.addMarker(markerOptions)
onDispose {
marker?.remove()
}
}
}
}
@Composable
private fun TopBar(hasSelected: Boolean, onCancel: () -> Unit, onConfirm: () -> Unit) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.shadow(elevation = 100.dp)
.statusBarsPadding()
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Text(
text = "取消",
color = Color.White,
fontSize = 16.sp,
modifier = Modifier.clickableWithoutRipple {
onCancel()
}
)
WeButton(
text = "确定",
size = ButtonSize.SMALL,
disabled = !hasSelected
) {
onConfirm()
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/navigation/LocationGraph.kt | 2462646150 | package top.chengdongqing.weui.feature.location.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import top.chengdongqing.weui.feature.location.screens.LocationPickerScreen
import top.chengdongqing.weui.feature.location.screens.LocationPreviewScreen
fun NavGraphBuilder.addLocationGraph() {
composable("location_preview") {
LocationPreviewScreen()
}
composable("location_picker") {
LocationPickerScreen()
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/utils/MapUtils.kt | 1841340054 | package top.chengdongqing.weui.feature.location.utils
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.location.Location
import android.net.Uri
import android.os.Build
import androidx.annotation.DrawableRes
import androidx.core.content.ContextCompat
import com.amap.api.maps.model.BitmapDescriptor
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.services.core.LatLonPoint
import top.chengdongqing.weui.core.utils.showToast
import top.chengdongqing.weui.feature.location.data.model.MapType
import java.net.URLEncoder
/**
* 调用地图软件导航到指定位置
*/
fun Context.navigateToLocation(
mapType: MapType,
location: LatLng,
name: String
) {
val uri: Uri = when (mapType) {
MapType.AMAP -> {
Uri.parse("amapuri://route/plan?dlat=${location.latitude}&dlon=${location.longitude}&dname=$name")
}
MapType.BAIDU -> {
val encodedName = URLEncoder.encode(name, "UTF-8")
Uri.parse("baidumap://map/direction?destination=latlng:${location.latitude},${location.longitude}|name:$encodedName")
}
MapType.TENCENT -> {
Uri.parse("qqmap://map/routeplan?to=$name&tocoord=${location.latitude},${location.longitude}")
}
MapType.GOOGLE -> {
Uri.parse("google.navigation:q=${location.latitude},${location.longitude}")
}
}
val intent = Intent(Intent.ACTION_VIEW, uri)
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent)
} else {
showToast("未安装${mapType.appName}地图")
}
}
/**
* 将指定的图片资源转为地图支持的bitmap
* 支持指定宽高、旋转角度
*/
fun createBitmapDescriptor(
context: Context,
@DrawableRes iconId: Int,
width: Int? = null,
height: Int? = null,
rotationAngle: Float? = null
): BitmapDescriptor? {
val drawable = ContextCompat.getDrawable(context, iconId) ?: return null
val originalWidth = width ?: drawable.intrinsicWidth
val originalHeight = height ?: drawable.intrinsicHeight
val bitmap = Bitmap.createBitmap(
originalWidth,
originalHeight,
Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
// 旋转
rotationAngle?.let {
val pivotX = originalWidth / 2f
val pivotY = originalHeight / 2f
canvas.save() // 保存画布当前的状态
canvas.rotate(it, pivotX, pivotY) // 应用旋转
}
drawable.setBounds(0, 0, originalWidth, originalHeight)
drawable.draw(canvas)
// 如果旋转了画布,现在恢复到之前保存的状态
rotationAngle?.let {
canvas.restore()
}
return BitmapDescriptorFactory.fromBitmap(bitmap)
}
// 判断位置是否加载完成
fun Location.isLoaded() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
this.isComplete
} else {
this.latitude != 0.0 && this.longitude != 0.0
}
fun LatLonPoint.toLatLng() = LatLng(latitude, longitude)
fun LatLng.toLatLonPoint() = LatLonPoint(latitude, longitude)
fun Location.toLatLng() = LatLng(latitude, longitude) |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/screens/LocationPreview.kt | 1809982875 | package top.chengdongqing.weui.feature.location.screens
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.amap.api.maps.model.LatLng
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem
import top.chengdongqing.weui.core.ui.components.cardlist.cartList
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.feature.location.data.model.LocationPreviewItem
import top.chengdongqing.weui.feature.location.preview.previewLocation
@Composable
fun LocationPreviewScreen() {
WeScreen(title = "LocationPreview", description = "查看位置", scrollEnabled = false) {
val context = LocalContext.current
val location = remember {
LocationPreviewItem(
name = "庐山国家级旅游风景名胜区",
address = "江西省九江市庐山市牯岭镇",
latLng = LatLng(29.5628, 115.9928),
zoom = 12f
)
}
LazyColumn(modifier = Modifier.cartList()) {
item {
location.apply {
WeCardListItem(label = "纬度", value = latLng.latitude.toString())
WeCardListItem(label = "经度", value = latLng.longitude.toString())
WeCardListItem(label = "位置名称", value = name)
WeCardListItem(label = "详细位置", value = address)
}
}
}
Spacer(modifier = Modifier.height(20.dp))
WeButton(text = "查看位置") {
context.previewLocation(location)
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/screens/LocationPicker.kt | 4042184178 | package top.chengdongqing.weui.feature.location.screens
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem
import top.chengdongqing.weui.core.ui.components.cardlist.cartList
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.feature.location.data.model.LocationItem
import top.chengdongqing.weui.feature.location.picker.rememberPickLocationLauncher
@Composable
fun LocationPickerScreen() {
WeScreen(title = "LocationPicker", description = "选择位置", scrollEnabled = false) {
var location by remember { mutableStateOf<LocationItem?>(null) }
location?.apply {
LazyColumn(modifier = Modifier.cartList()) {
item {
WeCardListItem(label = "纬度", value = latLng.latitude.toString())
WeCardListItem(label = "经度", value = latLng.longitude.toString())
WeCardListItem(label = "位置名称", value = name)
WeCardListItem(label = "详细位置", value = address ?: "")
}
}
Spacer(modifier = Modifier.height(20.dp))
}
val pickLocation = rememberPickLocationLauncher {
location = it
}
WeButton(text = "选择位置") {
pickLocation()
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/AMap.kt | 4057145372 | package top.chengdongqing.weui.feature.location
import android.Manifest
import android.content.ComponentCallbacks
import android.content.Context
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.MyLocation
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.Stable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapOptions
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapView
import com.amap.api.maps.MapsInitializer
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MyLocationStyle
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import top.chengdongqing.weui.core.ui.components.R
import top.chengdongqing.weui.core.utils.isTrue
import top.chengdongqing.weui.core.utils.showToast
import top.chengdongqing.weui.feature.location.utils.createBitmapDescriptor
import top.chengdongqing.weui.feature.location.utils.isLoaded
import top.chengdongqing.weui.feature.location.utils.toLatLng
@Composable
fun AMap(
modifier: Modifier = Modifier,
state: AMapState = rememberAMapState(),
controls: @Composable BoxScope.(AMap) -> Unit = {
LocationControl(it)
}
) {
val context = LocalContext.current
// 处理生命周期
LifecycleEffect(state.mapView)
// 处理定位权限
PermissionHandler {
setLocationArrow(state.map, context)
}
Box(modifier) {
AndroidView(
factory = { state.mapView },
modifier = Modifier.fillMaxSize()
)
controls(state.map)
}
}
@Composable
fun BoxScope.LocationControl(map: AMap, onClick: ((LatLng) -> Unit)? = null) {
val context = LocalContext.current
Box(
modifier = Modifier
.align(Alignment.BottomStart)
.offset(x = 12.dp, y = (-36).dp)
.size(40.dp)
.clip(RoundedCornerShape(8.dp))
.background(MaterialTheme.colorScheme.onBackground)
.clickable {
map.apply {
if (myLocation
?.isLoaded()
.isTrue()
) {
val latLng = myLocation.toLatLng()
animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16f))
onClick?.invoke(latLng)
} else {
context.showToast("定位中...")
}
}
},
contentAlignment = Alignment.Center
) {
Icon(
imageVector = Icons.Outlined.MyLocation,
contentDescription = "当前位置",
tint = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.size(26.dp)
)
}
}
private fun setLocationArrow(map: AMap, context: Context) {
map.apply {
myLocationStyle = MyLocationStyle().apply {
// 设置定位频率
interval(5000)
// 设置定位类型
myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER)
// 设置定位图标
val icon = createBitmapDescriptor(
context,
R.drawable.ic_location_rotatable,
90,
90,
-60f
)
myLocationIcon(icon)
// 去除精度圆圈
radiusFillColor(Color.TRANSPARENT)
strokeWidth(0f)
}
isMyLocationEnabled = true
}
}
@OptIn(ExperimentalPermissionsApi::class)
@Composable
private fun PermissionHandler(onGranted: (() -> Unit)? = null) {
val permissionState = rememberPermissionState(Manifest.permission.ACCESS_FINE_LOCATION) {
if (it) {
onGranted?.invoke()
}
}
LaunchedEffect(Unit) {
if (!permissionState.status.isGranted) {
permissionState.launchPermissionRequest()
} else {
onGranted?.invoke()
}
}
}
@Composable
private fun LifecycleEffect(mapView: MapView) {
val context = LocalContext.current
val lifecycle = LocalLifecycleOwner.current.lifecycle
val previousState = remember { mutableStateOf(Lifecycle.Event.ON_CREATE) }
DisposableEffect(context, lifecycle, mapView) {
val mapLifecycleObserver = mapView.lifecycleObserver(previousState)
val callbacks = mapView.componentCallbacks()
lifecycle.addObserver(mapLifecycleObserver)
context.registerComponentCallbacks(callbacks)
onDispose {
lifecycle.removeObserver(mapLifecycleObserver)
context.unregisterComponentCallbacks(callbacks)
}
}
DisposableEffect(mapView) {
onDispose {
mapView.onDestroy()
mapView.removeAllViews()
}
}
}
private fun MapView.lifecycleObserver(previousState: MutableState<Lifecycle.Event>): LifecycleEventObserver =
LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_CREATE -> {
if (previousState.value != Lifecycle.Event.ON_STOP) {
this.onCreate(Bundle())
}
}
Lifecycle.Event.ON_RESUME -> this.onResume()
Lifecycle.Event.ON_PAUSE -> this.onPause()
else -> {}
}
previousState.value = event
}
private fun MapView.componentCallbacks(): ComponentCallbacks =
object : ComponentCallbacks {
override fun onConfigurationChanged(config: Configuration) {}
override fun onLowMemory() {
[email protected]()
}
}
@Stable
interface AMapState {
/**
* 地图视图
*/
val mapView: MapView
/**
* 地图实例
*/
val map: AMap
}
@Composable
fun rememberAMapState(): AMapState {
val context = LocalContext.current
val isDarkTheme = isSystemInDarkTheme()
return remember {
AMapStateImpl(context, isDarkTheme)
}
}
private class AMapStateImpl(context: Context, isDarkTheme: Boolean) : AMapState {
override val mapView: MapView
override val map: AMap
init {
MapsInitializer.updatePrivacyShow(context, true, true)
MapsInitializer.updatePrivacyAgree(context, true)
val options = AMapOptions().apply {
// 设置logo位置
logoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT)
// 不显示缩放控件
zoomControlsEnabled(false)
// 设置地图类型
mapType(if (isDarkTheme) AMap.MAP_TYPE_NIGHT else AMap.MAP_TYPE_NORMAL)
}
mapView = MapView(context, options)
map = mapView.map
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/preview/LocationPreview.kt | 1952413649 | package top.chengdongqing.weui.feature.location.preview
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Navigation
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.MarkerOptions
import top.chengdongqing.weui.core.ui.components.R
import top.chengdongqing.weui.core.ui.components.actionsheet.ActionSheetItem
import top.chengdongqing.weui.core.ui.components.actionsheet.rememberActionSheetState
import top.chengdongqing.weui.feature.location.AMap
import top.chengdongqing.weui.feature.location.data.model.LocationPreviewItem
import top.chengdongqing.weui.feature.location.data.model.MapType
import top.chengdongqing.weui.feature.location.rememberAMapState
import top.chengdongqing.weui.feature.location.utils.createBitmapDescriptor
import top.chengdongqing.weui.feature.location.utils.navigateToLocation
@Composable
fun WeLocationPreview(location: LocationPreviewItem) {
val context = LocalContext.current
val state = rememberAMapState()
val map = state.map
LaunchedEffect(state) {
// 设置地图视野
map.moveCamera(CameraUpdateFactory.newLatLngZoom(location.latLng, location.zoom))
// 添加定位标记
val marker = MarkerOptions().apply {
position(location.latLng)
icon(
createBitmapDescriptor(
context,
R.drawable.ic_location_marker,
120,
120
)
)
}
map.addMarker(marker)
}
Column(modifier = Modifier.fillMaxSize()) {
AMap(modifier = Modifier.weight(1f), state)
BottomBar(location)
}
}
@Composable
private fun BottomBar(location: LocationPreviewItem) {
val actionSheet = rememberActionSheetState()
val mapOptions = remember {
listOf(
ActionSheetItem("高德地图"),
ActionSheetItem("百度地图"),
ActionSheetItem("腾讯地图"),
ActionSheetItem("谷歌地图"),
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surface)
.padding(horizontal = 20.dp, vertical = 40.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Column {
Text(
text = location.name,
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(14.dp))
location.address?.let {
Text(
text = it,
color = MaterialTheme.colorScheme.onSecondary,
fontSize = 14.sp
)
}
}
Column(horizontalAlignment = Alignment.CenterHorizontally) {
val context = LocalContext.current
Box(
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.background(MaterialTheme.colorScheme.background)
.clickable {
actionSheet.show(mapOptions) { index ->
context.navigateToLocation(
MapType.ofIndex(index)!!,
location.latLng,
location.name
)
}
},
contentAlignment = Alignment.Center
) {
Icon(
imageVector = Icons.Outlined.Navigation,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary,
modifier = Modifier.size(24.dp)
)
}
Spacer(modifier = Modifier.height(4.dp))
Text(text = "导航", color = MaterialTheme.colorScheme.onSecondary, fontSize = 14.sp)
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/preview/LocationPreviewActivity.kt | 466098523 | package top.chengdongqing.weui.feature.location.preview
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import top.chengdongqing.weui.core.ui.theme.WeUITheme
import top.chengdongqing.weui.feature.location.data.model.LocationPreviewItem
class LocationPreviewActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val location = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
intent.getParcelableExtra("location", LocationPreviewItem::class.java)
} else {
@Suppress("DEPRECATION")
intent.getParcelableExtra("location")
}!!
setContent {
WeUITheme {
WeLocationPreview(location)
}
}
}
companion object {
fun newIntent(context: Context) = Intent(context, LocationPreviewActivity::class.java)
}
}
fun Context.previewLocation(location: LocationPreviewItem) {
val intent = LocationPreviewActivity.newIntent(this).apply {
putExtra("location", location)
}
startActivity(intent)
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/repository/LocationRepositoryImpl.kt | 431801724 | package top.chengdongqing.weui.feature.location.data.repository
import android.content.Context
import androidx.datastore.preferences.core.edit
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.PoiItemV2
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeAddress
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.amap.api.services.poisearch.PoiResultV2
import com.amap.api.services.poisearch.PoiSearchV2
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import top.chengdongqing.weui.feature.location.data.model.LocationItem
import top.chengdongqing.weui.feature.location.utils.toLatLng
import top.chengdongqing.weui.feature.location.utils.toLatLonPoint
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
import kotlin.math.roundToInt
class LocationRepositoryImpl(private val context: Context) : LocationRepository {
override suspend fun locationToAddress(latLng: LatLng): RegeocodeAddress? =
withContext(Dispatchers.IO) {
suspendCoroutine { continuation ->
val geocoderSearch = GeocodeSearch(context)
geocoderSearch.setOnGeocodeSearchListener(object :
GeocodeSearch.OnGeocodeSearchListener {
override fun onRegeocodeSearched(result: RegeocodeResult?, resultCode: Int) {
if (resultCode == AMapException.CODE_AMAP_SUCCESS) {
continuation.resume(result?.regeocodeAddress)
} else {
continuation.resume(null)
}
}
override fun onGeocodeSearched(geocodeResult: GeocodeResult?, rCode: Int) {}
})
val query = RegeocodeQuery(
latLng.toLatLonPoint(),
100_000f,
GeocodeSearch.AMAP
)
geocoderSearch.getFromLocationAsyn(query)
}
}
override suspend fun search(
location: LatLng?,
keyword: String,
pageNum: Int,
pageSize: Int,
current: LatLng?
): List<LocationItem> = withContext(Dispatchers.IO) {
// 构建搜索参数:关键字,类别,区域
val query = PoiSearchV2.Query(keyword, "", "").apply {
this.pageNum = pageNum
this.pageSize = pageSize
}
val poiSearch = PoiSearchV2(context, query)
// 限定搜索范围:坐标,半径
if (location != null) {
poiSearch.bound = PoiSearchV2.SearchBound(location.toLatLonPoint(), 100_000)
}
suspendCoroutine { continuation ->
poiSearch.setOnPoiSearchListener(object : PoiSearchV2.OnPoiSearchListener {
override fun onPoiSearched(result: PoiResultV2?, resultCode: Int) {
if (resultCode == AMapException.CODE_AMAP_SUCCESS && result?.query != null) {
val items = result.pois.map { poiItem ->
LocationItem(
id = poiItem.poiId,
name = poiItem.title,
address = poiItem.adName,
distance = if (current != null) {
AMapUtils.calculateLineDistance(
current,
poiItem.latLonPoint.toLatLng()
).roundToInt()
} else null,
latLng = poiItem.latLonPoint.toLatLng()
)
}
continuation.resume(items)
} else {
continuation.resume(emptyList())
}
}
override fun onPoiItemSearched(poiItem: PoiItemV2?, rCode: Int) {}
})
poiSearch.searchPOIAsyn()
}
}
override val currentLocation: Flow<LatLng?>
get() = context.locationDataStore.data
.map { preferences ->
val latitude = preferences[PreferencesKeys.LATITUDE]
val longitude = preferences[PreferencesKeys.LONGITUDE]
if (latitude != null && longitude != null) {
LatLng(latitude, longitude)
} else {
null
}
}
override suspend fun saveCurrentLocation(latLng: LatLng) {
context.locationDataStore.edit { preferences ->
preferences[PreferencesKeys.LATITUDE] = latLng.latitude
preferences[PreferencesKeys.LONGITUDE] = latLng.longitude
}
}
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/repository/LocationDataStore.kt | 3452435093 | package top.chengdongqing.weui.feature.location.data.repository
import android.content.Context
import androidx.datastore.preferences.core.doublePreferencesKey
import androidx.datastore.preferences.preferencesDataStore
val Context.locationDataStore by preferencesDataStore(name = "location")
object PreferencesKeys {
val LATITUDE = doublePreferencesKey("latitude")
val LONGITUDE = doublePreferencesKey("longitude")
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/repository/LocationRepository.kt | 2499729512 | package top.chengdongqing.weui.feature.location.data.repository
import com.amap.api.maps.model.LatLng
import com.amap.api.services.geocoder.RegeocodeAddress
import kotlinx.coroutines.flow.Flow
import top.chengdongqing.weui.feature.location.data.model.LocationItem
interface LocationRepository {
suspend fun locationToAddress(latLng: LatLng): RegeocodeAddress?
suspend fun search(
location: LatLng?,
keyword: String,
pageNum: Int,
pageSize: Int,
current: LatLng?
): List<LocationItem>
val currentLocation: Flow<LatLng?>
suspend fun saveCurrentLocation(latLng: LatLng)
} |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/model/LocationItem.kt | 2848629460 | package top.chengdongqing.weui.feature.location.data.model
import android.os.Parcelable
import com.amap.api.maps.model.LatLng
import kotlinx.parcelize.Parcelize
@Parcelize
data class LocationItem(
val id: String? = null,
val name: String,
val address: String? = null,
val distance: Int? = null,
val latLng: LatLng
) : Parcelable |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/model/LocationPreviewItem.kt | 1800377301 | package top.chengdongqing.weui.feature.location.data.model
import android.os.Parcelable
import com.amap.api.maps.model.LatLng
import kotlinx.parcelize.Parcelize
@Parcelize
data class LocationPreviewItem(
val latLng: LatLng,
val name: String = "位置",
val address: String? = null,
val zoom: Float = 16f
) : Parcelable |
WeUI/feature/location/src/main/kotlin/top/chengdongqing/weui/feature/location/data/model/MapType.kt | 409035319 | package top.chengdongqing.weui.feature.location.data.model
enum class MapType(val appName: String) {
AMAP("高德"),
BAIDU("百度"),
TENCENT("腾讯"),
GOOGLE("谷歌");
companion object {
fun ofIndex(index: Int): MapType? {
return entries.getOrNull(index)
}
}
} |
WeUI/feature/network/src/androidTest/java/top/chengdongqing/weui/feature/network/ExampleInstrumentedTest.kt | 726907869 | package top.chengdongqing.weui.feature.network
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("top.chengdongqing.weui.feature.network.test", appContext.packageName)
}
} |
WeUI/feature/network/src/test/java/top/chengdongqing/weui/feature/network/ExampleUnitTest.kt | 2046744959 | package top.chengdongqing.weui.feature.network
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/websocket/WebSocket.kt | 4276150247 | package top.chengdongqing.weui.feature.network.websocket
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem
import top.chengdongqing.weui.core.ui.components.cardlist.cartList
import top.chengdongqing.weui.core.ui.components.input.WeTextarea
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.toast.ToastIcon
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
@Composable
fun WebSocketScreen(socketViewModel: WebSocketViewModel = viewModel()) {
WeScreen(title = "WebSocket", description = "双向通信", scrollEnabled = false) {
var connected by remember { mutableStateOf(false) }
DisposableEffect(Unit) {
onDispose {
socketViewModel.close()
}
}
if (!connected) {
UnconnectedScreen(socketViewModel) { connected = it }
} else {
ConnectedScreen(socketViewModel) { connected = it }
}
}
}
@Composable
private fun UnconnectedScreen(
socketViewModel: WebSocketViewModel,
setConnectState: (Boolean) -> Unit
) {
var connecting by remember { mutableStateOf(false) }
val toast = rememberToastState()
WeButton(
text = if (connecting) "连接中..." else "连接WebSocket",
loading = connecting
) {
connecting = true
socketViewModel.open("wss://echo.websocket.org", onFailure = {
toast.show("连接失败", ToastIcon.FAIL)
connecting = false
setConnectState(false)
}) {
toast.show("连接成功", ToastIcon.SUCCESS)
setConnectState(true)
}
}
}
@Composable
private fun ConnectedScreen(
socketViewModel: WebSocketViewModel,
setConnectState: (Boolean) -> Unit
) {
val keyboardController = LocalSoftwareKeyboardController.current
var text by remember { mutableStateOf("") }
val toast = rememberToastState()
WeTextarea(value = text, placeholder = "请输入内容") { text = it }
Spacer(modifier = Modifier.height(20.dp))
WeButton(text = "发送") {
if (text.isNotBlank()) {
socketViewModel.send(text)
keyboardController?.hide()
text = ""
} else {
toast.show("请输入内容", ToastIcon.FAIL)
}
}
Spacer(modifier = Modifier.height(20.dp))
WeButton(text = "断开连接", type = ButtonType.DANGER) {
socketViewModel.close()
setConnectState(false)
}
Spacer(modifier = Modifier.height(40.dp))
Text(text = "收到的消息", fontSize = 12.sp)
Spacer(modifier = Modifier.height(10.dp))
LazyColumn(modifier = Modifier.cartList()) {
itemsIndexed(socketViewModel.messages) { index, item ->
WeCardListItem(label = "${index + 1}", value = item)
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/websocket/WebSocketViewModel.kt | 3799347505 | package top.chengdongqing.weui.feature.network.websocket
import androidx.compose.runtime.mutableStateListOf
import androidx.lifecycle.ViewModel
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import top.chengdongqing.weui.core.utils.isTrue
class WebSocketViewModel : ViewModel() {
private var client: OkHttpClient? = null
private var webSocket: WebSocket? = null
val messages = mutableStateListOf<String>()
fun open(
url: String,
onFailure: ((Throwable) -> Unit)? = null,
onOpen: ((Response) -> Unit)? = null
) {
val request = Request.Builder().url(url).build()
val webSocketListener = TestWebSocketListener(
onOpen = {
onOpen?.invoke(it)
},
onFailure = {
onFailure?.invoke(it)
}
) {
messages.add(it)
}
client = OkHttpClient().apply {
webSocket = newWebSocket(request, webSocketListener)
}
}
fun send(message: String): Boolean {
return webSocket?.send(message).isTrue()
}
fun close() {
webSocket?.close(NORMAL_CLOSURE_STATUS, null)
client?.dispatcher?.executorService?.shutdown()
messages.clear()
}
}
private const val NORMAL_CLOSURE_STATUS = 1000
private class TestWebSocketListener(
val onOpen: (Response) -> Unit,
val onFailure: (Throwable) -> Unit,
val onMessage: (String) -> Unit
) : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
onOpen(response)
}
override fun onMessage(webSocket: WebSocket, text: String) {
onMessage(text)
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
t.printStackTrace()
onFailure(t)
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/navigation/NetworkGraph.kt | 3611544139 | package top.chengdongqing.weui.feature.network.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import top.chengdongqing.weui.feature.network.download.FileDownloadScreen
import top.chengdongqing.weui.feature.network.request.HttpRequestScreen
import top.chengdongqing.weui.feature.network.upload.FileUploadScreen
import top.chengdongqing.weui.feature.network.websocket.WebSocketScreen
fun NavGraphBuilder.addNetworkGraph() {
composable("http_request") {
HttpRequestScreen()
}
composable("file_upload") {
FileUploadScreen()
}
composable("file_download") {
FileDownloadScreen()
}
composable("web_socket") {
WebSocketScreen()
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/repository/DownloadRepositoryImpl.kt | 1847294468 | package top.chengdongqing.weui.feature.network.download.repository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import top.chengdongqing.weui.feature.network.download.retrofit.DownloadService
import top.chengdongqing.weui.feature.network.download.retrofit.RetrofitManger
import java.io.IOException
class DownloadRepositoryImpl : DownloadRepository {
private val downloadService by lazy {
RetrofitManger.retrofit.create(DownloadService::class.java)
}
override suspend fun downloadFile(filename: String): ResponseBody? {
return withContext(Dispatchers.IO) {
try {
downloadService.downloadFile(filename)
} catch (e: IOException) {
null
}
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/repository/DownloadRepository.kt | 2089654030 | package top.chengdongqing.weui.feature.network.download.repository
import okhttp3.ResponseBody
interface DownloadRepository {
suspend fun downloadFile(filename: String): ResponseBody?
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/retrofit/DownloadService.kt | 1203405502 | package top.chengdongqing.weui.feature.network.download.retrofit
import okhttp3.ResponseBody
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Streaming
interface DownloadService {
@Streaming
@GET("{filename}")
suspend fun downloadFile(@Path("filename") filename: String): ResponseBody
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/retrofit/RetrofitManger.kt | 787762575 | package top.chengdongqing.weui.feature.network.download.retrofit
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
internal object RetrofitManger {
private const val BASE_URL = "https://s1.xiaomiev.com/activity-outer-assets/web/home/"
val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/FileDownload.kt | 639498166 | package top.chengdongqing.weui.feature.network.download
import androidx.compose.foundation.Image
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.ImageBitmap
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.toast.ToastIcon
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
@Composable
fun FileDownloadScreen(downloadViewModel: DownloadViewModel = viewModel()) {
WeScreen(title = "FileDownload", description = "文件下载") {
var bitmap by remember { mutableStateOf<ImageBitmap?>(null) }
var downloading by remember { mutableStateOf(false) }
val coroutineScope = rememberCoroutineScope()
val toast = rememberToastState()
bitmap?.let {
Image(bitmap = it, contentDescription = null)
} ?: WeButton(
text = if (downloading) "下载中..." else "下载图片",
loading = downloading
) {
downloading = true
coroutineScope.launch {
bitmap = downloadViewModel.downloadFile("section1.jpg").also {
if (it == null) {
toast.show("下载失败", ToastIcon.FAIL)
}
}
downloading = false
}
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/download/DownloadViewModel.kt | 3213125138 | package top.chengdongqing.weui.feature.network.download
import android.graphics.BitmapFactory
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.lifecycle.ViewModel
import top.chengdongqing.weui.feature.network.download.repository.DownloadRepositoryImpl
class DownloadViewModel : ViewModel() {
private val downloadRepository by lazy {
DownloadRepositoryImpl()
}
suspend fun downloadFile(filename: String): ImageBitmap? {
return downloadRepository.downloadFile(filename)?.byteStream()?.use {
BitmapFactory.decodeStream(it).asImageBitmap()
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/HttpRequest.kt | 2926749040 | package top.chengdongqing.weui.feature.network.request
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.gson.GsonBuilder
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.toast.ToastIcon
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
@Composable
fun HttpRequestScreen(viewModel: CartViewModel = viewModel()) {
WeScreen(
title = "HttpRequest",
description = "HTTP请求(OkHttp+Retrofit)",
scrollEnabled = false
) {
val toast = rememberToastState()
val coroutineScope = rememberCoroutineScope()
var content by remember { mutableStateOf<String?>(null) }
var loading by remember { mutableStateOf(false) }
WeButton(
"查询推荐的商品",
loading = loading,
width = 200.dp,
modifier = Modifier.align(Alignment.CenterHorizontally)
) {
loading = true
coroutineScope.launch {
val res = viewModel.fetchRecommendProducts()
loading = false
if (res?.code == 200) {
val gson = GsonBuilder().setPrettyPrinting().create()
content = gson.toJson(res)
} else {
toast.show("请求失败", ToastIcon.FAIL)
}
}
}
content?.let {
Spacer(modifier = Modifier.height(40.dp))
Box(
modifier = Modifier
.background(
MaterialTheme.colorScheme.onBackground,
RoundedCornerShape(6.dp)
)
.padding(20.dp)
.verticalScroll(rememberScrollState())
) {
Text(
text = it,
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 12.sp
)
}
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/retrofit/CartService.kt | 3609878434 | package top.chengdongqing.weui.feature.network.request.retrofit
import retrofit2.http.GET
import retrofit2.http.Header
import top.chengdongqing.weui.feature.network.request.data.model.RecommendItem
import top.chengdongqing.weui.feature.network.request.data.model.Result
interface CartService {
@GET("rec/cartempty")
suspend fun fetchRecommendProducts(
@Header("Referer") referer: String = "https://www.mi.com"
): Result<List<RecommendItem>>
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/retrofit/RetrofitManger.kt | 2540040301 | package top.chengdongqing.weui.feature.network.request.retrofit
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
internal object RetrofitManger {
private const val BASE_URL = "https://api2.order.mi.com/"
val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/CartViewModel.kt | 3023221031 | package top.chengdongqing.weui.feature.network.request
import androidx.lifecycle.ViewModel
import top.chengdongqing.weui.feature.network.request.data.model.RecommendItem
import top.chengdongqing.weui.feature.network.request.data.model.Result
import top.chengdongqing.weui.feature.network.request.data.repository.CartRepositoryImpl
class CartViewModel : ViewModel() {
private val cartRepository by lazy {
CartRepositoryImpl()
}
suspend fun fetchRecommendProducts(): Result<List<RecommendItem>>? {
return cartRepository.fetchRecommendProducts()
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/data/repository/CartRepositoryImpl.kt | 317352688 | package top.chengdongqing.weui.feature.network.request.data.repository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import top.chengdongqing.weui.feature.network.request.data.model.RecommendItem
import top.chengdongqing.weui.feature.network.request.data.model.Result
import top.chengdongqing.weui.feature.network.request.retrofit.CartService
import top.chengdongqing.weui.feature.network.request.retrofit.RetrofitManger
import java.io.IOException
class CartRepositoryImpl : CartRepository {
private val cartService by lazy {
RetrofitManger.retrofit.create(CartService::class.java)
}
override suspend fun fetchRecommendProducts(): Result<List<RecommendItem>>? {
return withContext(Dispatchers.IO) {
try {
cartService.fetchRecommendProducts()
} catch (e: IOException) {
null
}
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/data/repository/CartRepository.kt | 254195160 | package top.chengdongqing.weui.feature.network.request.data.repository
import top.chengdongqing.weui.feature.network.request.data.model.RecommendItem
import top.chengdongqing.weui.feature.network.request.data.model.Result
interface CartRepository {
suspend fun fetchRecommendProducts(): Result<List<RecommendItem>>?
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/data/model/Result.kt | 2520023981 | package top.chengdongqing.weui.feature.network.request.data.model
data class Result<out T>(
val code: Int,
val msg: String? = null,
val data: T? = null
) |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/request/data/model/RecommendItem.kt | 4121782359 | package top.chengdongqing.weui.feature.network.request.data.model
import com.google.gson.annotations.SerializedName
import java.math.BigDecimal
data class RecommendItem(
val algorithm: Int,
val eid: String,
val info: Product
) {
data class Product(
@SerializedName("product_id")
val productId: Long,
@SerializedName("category_id")
val categoryId: Long,
val image: String,
@SerializedName("market_price")
val marketPrice: BigDecimal,
val price: BigDecimal,
val name: String,
@SerializedName("goods_list")
val goodsList: List<Long>
)
}
|
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/upload/retrofit/UploadService.kt | 2724048868 | package top.chengdongqing.weui.feature.network.upload.retrofit
import okhttp3.MultipartBody
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
import top.chengdongqing.weui.feature.network.upload.data.model.UploadResult
interface UploadService {
@Multipart
@POST("upload")
suspend fun uploadFile(@Part file: MultipartBody.Part): UploadResult
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/upload/retrofit/RetrofitManger.kt | 3421334363 | package top.chengdongqing.weui.feature.network.upload.retrofit
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
internal object RetrofitManger {
private const val BASE_URL = "https://unidemo.dcloud.net.cn/"
val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/upload/UploadViewModel.kt | 3488730213 | package top.chengdongqing.weui.feature.network.upload
import android.app.Application
import android.net.Uri
import android.provider.MediaStore
import androidx.lifecycle.AndroidViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import top.chengdongqing.weui.feature.network.upload.data.model.UploadResult
import top.chengdongqing.weui.feature.network.upload.data.repository.UploadRepositoryImpl
import java.io.File
class UploadViewModel(private val application: Application) : AndroidViewModel(application) {
private val uploadRepository by lazy {
UploadRepositoryImpl()
}
suspend fun uploadFile(uri: Uri): UploadResult.Files.FileItem? {
return withContext(Dispatchers.IO) {
// 查询文件元数据
val deferredMetadata = async<Pair<String, String>?> {
val projection = arrayOf(
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.SIZE,
MediaStore.Files.FileColumns.MIME_TYPE
)
application.contentResolver.query(uri, projection, null, null)?.use { cursor ->
val nameColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
val mimeTypeColumn =
cursor.getColumnIndex(MediaStore.Files.FileColumns.MIME_TYPE)
if (cursor.moveToFirst()) {
val fileName = cursor.getString(nameColumn)
val mimeType = cursor.getString(mimeTypeColumn)
return@async fileName to mimeType
}
}
null
}
// 构建临时文件
val deferredFile = async {
application.contentResolver.openInputStream(uri)?.use { inputStream ->
val tempFile = File.createTempFile("uploadFile", null).apply {
deleteOnExit()
}
inputStream.copyTo(tempFile.outputStream())
return@async tempFile
}
null
}
val metadata = deferredMetadata.await()
val file = deferredFile.await()
if (metadata != null && file != null) {
val requestFile = file.asRequestBody(metadata.second.toMediaType())
val body = MultipartBody.Part.createFormData("file", metadata.first, requestFile)
uploadRepository.uploadFile(body)?.files?.file
} else {
null
}
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/upload/FileUpload.kt | 4072946607 | package top.chengdongqing.weui.feature.network.upload
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.gson.GsonBuilder
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.data.model.VisualMediaType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.mediapicker.rememberPickMediasLauncher
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.toast.ToastIcon
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
@Composable
fun FileUploadScreen(uploadViewModel: UploadViewModel = viewModel()) {
WeScreen(title = "FileUpload", description = "文件上传") {
var uploading by remember { mutableStateOf(false) }
var content by remember { mutableStateOf<String?>(null) }
val toast = rememberToastState()
val coroutineScope = rememberCoroutineScope()
val pickMedia = rememberPickMediasLauncher {
uploading = true
coroutineScope.launch {
uploadViewModel.uploadFile(it.first().uri)?.let { res ->
val gson = GsonBuilder().setPrettyPrinting().create()
content = gson.toJson(res)
toast.show("上传成功", ToastIcon.SUCCESS)
} ?: toast.show("上传失败", ToastIcon.FAIL)
uploading = false
}
}
WeButton(
text = if (uploading) "上传中..." else "上传图片",
loading = uploading,
modifier = Modifier.align(Alignment.CenterHorizontally)
) {
pickMedia(VisualMediaType.IMAGE, 1)
}
content?.let {
Spacer(modifier = Modifier.height(40.dp))
Box(
modifier = Modifier
.fillMaxWidth()
.background(
MaterialTheme.colorScheme.onBackground,
RoundedCornerShape(6.dp)
)
.padding(20.dp),
contentAlignment = Alignment.Center
) {
Text(
text = it,
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 12.sp
)
}
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/upload/data/repository/UploadRepository.kt | 2500824966 | package top.chengdongqing.weui.feature.network.upload.data.repository
import okhttp3.MultipartBody
import top.chengdongqing.weui.feature.network.upload.data.model.UploadResult
interface UploadRepository {
suspend fun uploadFile(file: MultipartBody.Part): UploadResult?
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/upload/data/repository/UploadRepositoryImpl.kt | 3470940661 | package top.chengdongqing.weui.feature.network.upload.data.repository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MultipartBody
import top.chengdongqing.weui.feature.network.upload.data.model.UploadResult
import top.chengdongqing.weui.feature.network.upload.retrofit.RetrofitManger
import top.chengdongqing.weui.feature.network.upload.retrofit.UploadService
import java.io.IOException
class UploadRepositoryImpl : UploadRepository {
private val uploadService by lazy {
RetrofitManger.retrofit.create(UploadService::class.java)
}
override suspend fun uploadFile(file: MultipartBody.Part): UploadResult? {
return withContext(Dispatchers.IO) {
try {
uploadService.uploadFile(file)
} catch (e: IOException) {
null
}
}
}
} |
WeUI/feature/network/src/main/kotlin/top/chengdongqing/weui/feature/network/upload/data/model/UploadResult.kt | 2764329616 | package top.chengdongqing.weui.feature.network.upload.data.model
data class UploadResult(
val error: String,
val strings: List<String>,
val files: Files
) {
data class Files(
val file: FileItem
) {
data class FileItem(
val name: String,
val size: Long,
val type: String,
val url: String
)
}
} |
WeUI/feature/basic/src/androidTest/java/top/chengdongqing/weui/feature/basic/ExampleInstrumentedTest.kt | 16267976 | package top.chengdongqing.weui.feature.basic
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("top.chengdongqing.weui.feature.basic.test", appContext.packageName)
}
} |
WeUI/feature/basic/src/test/java/top/chengdongqing/weui/feature/basic/ExampleUnitTest.kt | 244264812 | package top.chengdongqing.weui.feature.basic
import org.junit.Assert.*
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/navigation/BasicGraph.kt | 3423233429 | package top.chengdongqing.weui.feature.basic.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import top.chengdongqing.weui.feature.basic.screens.BadgeScreen
import top.chengdongqing.weui.feature.basic.screens.LoadMoreScreen
import top.chengdongqing.weui.feature.basic.screens.LoadingScreen
import top.chengdongqing.weui.feature.basic.screens.ProgressScreen
import top.chengdongqing.weui.feature.basic.screens.RefreshViewScreen
import top.chengdongqing.weui.feature.basic.screens.SkeletonScreen
import top.chengdongqing.weui.feature.basic.screens.StepsScreen
import top.chengdongqing.weui.feature.basic.screens.SwipeActionScreen
import top.chengdongqing.weui.feature.basic.screens.SwiperScreen
import top.chengdongqing.weui.feature.basic.screens.TabViewScreen
import top.chengdongqing.weui.feature.basic.screens.TreeScreen
fun NavGraphBuilder.addBasicGraph() {
composable("badge") {
BadgeScreen()
}
composable("loading") {
LoadingScreen()
}
composable("load_more") {
LoadMoreScreen()
}
composable("progress") {
ProgressScreen()
}
composable("steps") {
StepsScreen()
}
composable("swiper") {
SwiperScreen()
}
composable("refresh_view") {
RefreshViewScreen()
}
composable("tab_view") {
TabViewScreen()
}
composable("swipe_action") {
SwipeActionScreen()
}
composable("skeleton") {
SkeletonScreen()
}
composable("tree") {
TreeScreen()
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/TabView.kt | 2457096334 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.tabview.WeTabView
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TabViewScreen() {
WeScreen(
title = "TabView",
description = "选项卡视图",
padding = PaddingValues(0.dp),
scrollEnabled = false
) {
val options = remember {
List(10) { "Tab ${it + 1}" }
}
WeTabView(options) { index ->
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(
text = (index + 1).toString(),
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 60.sp
)
}
}
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/LoadMore.kt | 282865456 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.runtime.Composable
import top.chengdongqing.weui.core.ui.components.loading.LoadMoreType
import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
@Composable
fun LoadMoreScreen() {
WeScreen(title = "LoadMore", description = "加载更多") {
WeLoadMore(type = LoadMoreType.LOADING)
WeLoadMore(type = LoadMoreType.EMPTY_DATA)
WeLoadMore(type = LoadMoreType.ALL_LOADED)
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/SwipeAction.kt | 3976580618 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.gestures.animateTo
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.FavoriteBorder
import androidx.compose.material.icons.outlined.StarOutline
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.data.model.DragAnchor
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.swipeaction.SwipeActionItem
import top.chengdongqing.weui.core.ui.components.swipeaction.SwipeActionStyle
import top.chengdongqing.weui.core.ui.components.swipeaction.SwipeActionType
import top.chengdongqing.weui.core.ui.components.swipeaction.WeSwipeAction
import top.chengdongqing.weui.core.ui.components.swipeaction.rememberSwipeActionState
import top.chengdongqing.weui.core.ui.components.toast.ToastState
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
@Composable
fun SwipeActionScreen() {
WeScreen(
title = "SwipeAction",
description = "滑动操作"
) {
val options = remember {
listOf(
SwipeActionItem(
type = SwipeActionType.PLAIN,
label = "喜欢",
icon = Icons.Outlined.FavoriteBorder
),
SwipeActionItem(
type = SwipeActionType.WARNING,
label = "收藏",
icon = Icons.Outlined.StarOutline
),
SwipeActionItem(
type = SwipeActionType.DANGER,
label = "删除",
icon = Icons.Outlined.Delete
)
)
}
val toast = rememberToastState()
LabelStyleDemo(options, toast)
Spacer(modifier = Modifier.height(40.dp))
IconStyleDemo(options, toast)
Spacer(modifier = Modifier.height(40.dp))
ControllableDemo(options, toast)
}
}
@Composable
private fun LabelStyleDemo(options: List<SwipeActionItem>, toast: ToastState) {
WeSwipeAction(
startOptions = options.slice(0..1),
endOptions = options,
onStartTap = {
toast.show("你点击了左边的${options[it].label}")
},
onEndTap = {
toast.show("你点击了右边的${options[it].label}")
}
) {
Text(text = "文字按钮(左右滑动)", color = MaterialTheme.colorScheme.onPrimary)
}
}
@Composable
private fun IconStyleDemo(options: List<SwipeActionItem>, toast: ToastState) {
WeSwipeAction(
startOptions = options,
endOptions = options,
style = SwipeActionStyle.ICON,
height = 70.dp,
onStartTap = {
toast.show("你点击了左边的${options[it].label}")
},
onEndTap = {
toast.show("你点击了右边的${options[it].label}")
}
) {
Text(text = "图标按钮(左右滑动)", color = MaterialTheme.colorScheme.onPrimary)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ControllableDemo(options: List<SwipeActionItem>, toast: ToastState) {
val options1 = remember { options.slice(1..2) }
val swipeActionState = rememberSwipeActionState(
initialValue = DragAnchor.End,
endActionCount = options1.size
)
val coroutineScope = rememberCoroutineScope()
WeButton(text = "切换状态", type = ButtonType.PLAIN) {
coroutineScope.launch {
val value = if (swipeActionState.draggableState.currentValue == DragAnchor.End) {
DragAnchor.Center
} else {
DragAnchor.End
}
swipeActionState.draggableState.animateTo(value)
}
}
Spacer(modifier = Modifier.height(20.dp))
WeSwipeAction(
startOptions = options1,
endOptions = options1,
swipeActionState = swipeActionState,
onStartTap = {
toast.show("你点击了左边的${options1[it].label}")
},
onEndTap = {
toast.show("你点击了右边的${options1[it].label}")
}
) {
Text(text = "变量控制", color = MaterialTheme.colorScheme.onPrimary)
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/Progress.kt | 3683873345 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.progress.WeCircleProgress
import top.chengdongqing.weui.core.ui.components.progress.WeDashboardProgress
import top.chengdongqing.weui.core.ui.components.progress.WeProgress
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import java.util.Timer
import kotlin.concurrent.timerTask
@Composable
fun ProgressScreen() {
WeScreen(title = "Progress", description = "进度条") {
WeProgress(20f, null)
WeProgress(44.57898f)
var value by remember { mutableFloatStateOf(0f) }
var loading by remember { mutableStateOf(false) }
val coroutineScope = rememberCoroutineScope()
WeProgress(value)
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround
) {
WeCircleProgress(value)
WeDashboardProgress(value)
}
Spacer(modifier = Modifier.height(60.dp))
WeButton(
text = if (!loading) "上传" else "上传中...",
loading = loading
) {
value = 0f
loading = true
coroutineScope.launch {
val timer = Timer()
timer.schedule(timerTask {
if (value < 100) {
value += 2
} else {
timer.cancel()
loading = false
}
}, 0L, 50L)
}
}
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/RefreshView.kt | 2877022079 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import kotlinx.coroutines.delay
import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem
import top.chengdongqing.weui.core.ui.components.cardlist.cartList
import top.chengdongqing.weui.core.ui.components.loading.WeLoadMore
import top.chengdongqing.weui.core.ui.components.refreshview.WeRefreshView
import top.chengdongqing.weui.core.ui.components.refreshview.rememberLoadMoreState
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
@Composable
fun RefreshViewScreen() {
WeScreen(title = "RefreshView", description = "可刷新视图", scrollEnabled = false) {
val listState = rememberLazyListState()
val listItems = remember {
mutableStateListOf<String>().apply {
addAll(List(30) { "${it + 1}" })
}
}
val loadMoreState = rememberLoadMoreState {
delay(2000)
listItems.addAll(List(30) { index -> "${listItems.size + index + 1}" })
}
WeRefreshView(
modifier = Modifier.nestedScroll(loadMoreState.nestedScrollConnection),
onRefresh = {
delay(2000)
listItems.clear()
listItems.addAll(List(30) { "${it + 1}" })
}
) {
LazyColumn(state = listState, modifier = Modifier.cartList()) {
items(listItems, key = { it }) {
WeCardListItem(label = "第${it}行")
}
item {
if (loadMoreState.isLoadingMore) {
WeLoadMore(listState = listState)
}
}
}
}
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/Steps.kt | 767736924 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.steps.WeSteps
@Composable
fun StepsScreen() {
WeScreen(title = "Steps", description = "步骤条") {
var step by remember { mutableIntStateOf(0) }
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround
) {
WeSteps(
value = step,
options = listOf(
{
Column {
Text(text = "步骤一", color = MaterialTheme.colorScheme.onPrimary)
Text(
text = "描述内容详情",
color = MaterialTheme.colorScheme.secondary,
fontSize = 14.sp
)
}
},
{
Column(modifier = Modifier.height(120.dp)) {
Text(text = "步骤二", color = MaterialTheme.colorScheme.onPrimary)
Text(
text = "描述内容详情",
color = MaterialTheme.colorScheme.onSecondary,
fontSize = 14.sp
)
}
},
{
Column {
Text(text = "步骤三", color = MaterialTheme.colorScheme.onPrimary)
Text(
text = "描述内容详情",
color = MaterialTheme.colorScheme.secondary,
fontSize = 14.sp
)
}
},
{
Column {
Text(text = "步骤四", color = MaterialTheme.colorScheme.onPrimary)
}
}
)
)
WeSteps(
value = step,
options = listOf(null, null, null, null)
)
}
Column {
WeSteps(
value = step,
options = listOf(
{
Text(text = "步骤一", color = MaterialTheme.colorScheme.onPrimary)
},
{
Text(text = "步骤二", color = MaterialTheme.colorScheme.onPrimary)
},
{
Column(
modifier = Modifier.width(180.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "步骤三", color = MaterialTheme.colorScheme.onPrimary)
Text(
text = "描述内容详情",
color = MaterialTheme.colorScheme.onSecondary,
fontSize = 14.sp
)
}
}
),
isVertical = false
)
Spacer(modifier = Modifier.height(20.dp))
WeSteps(
value = step,
options = listOf(null, null, null, null),
isVertical = false
)
Spacer(modifier = Modifier.height(40.dp))
WeButton(
text = "更新状态",
modifier = Modifier.align(alignment = Alignment.CenterHorizontally)
) {
if (step < 3) {
step++
} else {
step = 0
}
}
}
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/Loading.kt | 709921064 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.loading.DotDanceLoading
import top.chengdongqing.weui.core.ui.components.loading.MiLoadingMobile
import top.chengdongqing.weui.core.ui.components.loading.MiLoadingWeb
import top.chengdongqing.weui.core.ui.components.loading.WeLoading
import top.chengdongqing.weui.core.ui.components.loading.WeLoadingMP
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
@Composable
fun LoadingScreen() {
WeScreen(
title = "Loading",
description = "加载中",
verticalArrangement = Arrangement.spacedBy(40.dp)
) {
WeLoading()
WeLoading(size = 32.dp, color = MaterialTheme.colorScheme.primary)
MiLoadingMobile()
WeLoadingMP()
DotDanceLoading()
MiLoadingWeb()
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/Swiper.kt | 4092843885 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.swiper.WeSwiper
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun SwiperScreen() {
WeScreen(title = "Swiper", description = "滑动视图") {
val banners = remember {
listOf(
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/0b2bb13c396cc6205dd91da3a91a275a.jpg?f=webp&w=1080&h=540&bg=A8D4D5",
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/1ab1ffaaeb5ca4c02674e9f35b1fd17c.jpg?f=webp&w=1080&h=540&bg=59A5FD",
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/37bd342303515c7a1a54681599e319a1.jpg?f=webp&w=1080&h=540&bg=56B6A8",
"https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/a2b3ab270e5ae4c9e85d6607cdb97008.jpg?f=webp&w=1080&h=540&bg=DC85AF"
)
}
val state = rememberPagerState { banners.size }
var isCardMode by remember { mutableStateOf(false) }
WeSwiper(
state = state,
options = banners,
modifier = Modifier.clip(RoundedCornerShape(6.dp)),
contentPadding = if (isCardMode) PaddingValues(horizontal = 50.dp) else PaddingValues(0.dp),
pageSpacing = if (isCardMode) 0.dp else 20.dp
) { index, item ->
val animatedScale by animateFloatAsState(
targetValue = if (index == state.currentPage || !isCardMode) 1f else 0.85f,
label = ""
)
AsyncImage(
model = item,
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(2 / 1f)
.scale(animatedScale)
.clip(RoundedCornerShape(6.dp))
)
}
Spacer(modifier = Modifier.height(40.dp))
WeButton(text = "切换样式", type = ButtonType.PLAIN) {
isCardMode = !isCardMode
}
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/Tree.kt | 57094158 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.tree.WeTreeNode
import top.chengdongqing.weui.feature.basic.R
@Composable
fun TreeScreen() {
WeScreen(title = "Tree", description = "树型菜单", horizontalAlignment = Alignment.Start) {
WeTreeNode("WeUI") {
WeTreeNode("安装包") {
repeat(10) { index ->
ApkNode("v${index + 1}.0")
}
WeTreeNode("未发布的版本") {
ApkNode("alpha01")
ApkNode("beta05")
}
}
}
WeTreeNode("文档") {
DocumentNode("个人简历.pdf")
DocumentNode("技术分享.pptx")
DocumentNode("销售账单.xlsx")
DocumentNode("开发手册.docx")
}
}
}
@Composable
private fun DocumentNode(name: String) {
WeTreeNode(
label = name,
labelSize = 14.sp,
icon = {
Image(
painter = painterResource(id = R.drawable.ic_document),
contentDescription = null,
modifier = Modifier.size(20.dp)
)
}
)
}
@Composable
private fun ApkNode(version: String) {
WeTreeNode(
label = "WeUI_$version.apk",
labelSize = 14.sp,
icon = {
Image(
painter = painterResource(id = R.drawable.ic_apk),
contentDescription = null,
modifier = Modifier.size(20.dp)
)
}
)
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/Badge.kt | 253078156 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.badge.WeBadge
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
@Composable
fun BadgeScreen() {
WeScreen(
title = "Badge",
description = "徽章",
padding = PaddingValues(bottom = 100.dp),
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
WeBadge {
WeButton(text = "按钮")
}
WeBadge("8", size = 20.dp) {
WeButton(text = "按钮")
}
WeBadge("New", size = 20.dp, alignment = Alignment.BottomEnd) {
WeButton(text = "按钮")
}
WeBadge(alignment = Alignment.TopStart, size = 5.dp) {
WeButton(text = "按钮")
}
WeBadge(
"8",
size = 20.dp,
color = MaterialTheme.colorScheme.primary,
alignment = Alignment.BottomStart
) {
WeButton(text = "按钮")
}
WeBadge("New", size = 20.dp, alignment = Alignment.CenterEnd) {
WeButton(text = "按钮")
}
WeBadge(alignment = Alignment.CenterEnd) {
WeButton(text = "按钮")
}
WeBadge(alignment = Alignment.CenterStart) {
WeButton(text = "按钮")
}
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround
) {
Text(text = "Android开发工程师", color = MaterialTheme.colorScheme.onPrimary)
WeBadge("New", 20.dp, alignment = Alignment.Center)
}
}
} |
WeUI/feature/basic/src/main/kotlin/top/chengdongqing/weui/feature/basic/screens/Skeleton.kt | 3274147376 | package top.chengdongqing.weui.feature.basic.screens
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.skeleton.WeSkeleton
import top.chengdongqing.weui.core.ui.components.switch.WeSwitch
@Composable
fun SkeletonScreen() {
WeScreen(
title = "Skeleton",
description = "骨架屏",
containerColor = MaterialTheme.colorScheme.surface
) {
var isActive by remember { mutableStateOf(true) }
ActiveControl(isActive) { isActive = it }
Spacer(modifier = Modifier.height(60.dp))
Content(isActive)
}
}
@Composable
private fun ColumnScope.ActiveControl(
value: Boolean,
onChange: (Boolean) -> Unit
) {
Row(
modifier = Modifier.align(Alignment.CenterHorizontally),
verticalAlignment = Alignment.CenterVertically
) {
Text(text = "加载中", color = MaterialTheme.colorScheme.onPrimary, fontSize = 16.sp)
Spacer(modifier = Modifier.width(30.dp))
WeSwitch(checked = value, onChange = onChange)
}
}
@Composable
private fun Content(isActive: Boolean) {
Column {
WeSkeleton.Rectangle(isActive)
Spacer(modifier = Modifier.padding(8.dp))
WeSkeleton.RectangleLineLong(isActive)
Spacer(modifier = Modifier.padding(4.dp))
WeSkeleton.RectangleLineShort(isActive)
}
Spacer(modifier = Modifier.height(48.dp))
Row {
WeSkeleton.Circle(isActive)
Spacer(modifier = Modifier.padding(4.dp))
Column {
Spacer(modifier = Modifier.padding(8.dp))
WeSkeleton.RectangleLineLong(isActive)
Spacer(modifier = Modifier.padding(4.dp))
WeSkeleton.RectangleLineShort(isActive)
}
}
Spacer(modifier = Modifier.height(48.dp))
Row {
WeSkeleton.Square(isActive)
Spacer(modifier = Modifier.padding(4.dp))
Column {
Spacer(modifier = Modifier.padding(8.dp))
WeSkeleton.RectangleLineLong(isActive)
Spacer(modifier = Modifier.padding(4.dp))
WeSkeleton.RectangleLineShort(isActive)
}
}
Spacer(modifier = Modifier.height(48.dp))
} |
WeUI/feature/charts/src/androidTest/java/top/chengdongqing/weui/feature/charts/ExampleInstrumentedTest.kt | 992967890 | package top.chengdongqing.weui.feature.charts
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("top.chengdongqing.weui.feature.charts.test", appContext.packageName)
}
} |
WeUI/feature/charts/src/test/java/top/chengdongqing/weui/feature/charts/ExampleUnitTest.kt | 3684072035 | package top.chengdongqing.weui.feature.charts
import org.junit.Assert.*
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/BarChart.kt | 2488867657 | package top.chengdongqing.weui.feature.charts
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.utils.format
import top.chengdongqing.weui.feature.charts.model.ChartData
@Composable
fun WeBarChart(
dataSource: List<ChartData>,
modifier: Modifier = Modifier,
height: Dp = 300.dp,
barWidthRange: IntRange = 2..20,
color: Color = MaterialTheme.colorScheme.primary.copy(0.8f),
animationSpec: AnimationSpec<Float> = tween(durationMillis = 800),
formatter: (Float) -> String = { it.format() }
) {
val textMeasurer = rememberTextMeasurer()
// 刻度颜色
val labelColor = MaterialTheme.colorScheme.onSecondary
// 数据最大值
val maxValue = remember(dataSource) { dataSource.maxOfOrNull { it.value } ?: 1f }
// 每个数据项的动画实例
val animatedHeights = remember(dataSource.size) { dataSource.map { Animatable(0f) } }
// 数据变化后执行动画
LaunchedEffect(dataSource) {
animatedHeights.forEachIndexed { index, item ->
launch {
item.animateTo(
targetValue = dataSource[index].value / maxValue,
animationSpec = animationSpec
)
}
}
}
Canvas(
modifier = modifier
.fillMaxWidth()
.padding(top = 20.dp)
.height(height)
) {
// 柱宽
val barWidth = (size.width / (dataSource.size * 2f)).coerceIn(
barWidthRange.first.dp.toPx(),
barWidthRange.last.dp.toPx()
)
// 柱间距
val barSpace = (size.width - barWidth * dataSource.size) / dataSource.size
// 绘制X轴
drawXAxis(
labels = dataSource.map { it.label },
barWidth,
barSpace,
axisColor = color,
labelColor,
textMeasurer
)
// 绘制柱状图
drawBars(
animatedHeights,
dataSource,
barWidth,
barSpace,
barColor = color,
textMeasurer,
formatter
)
}
}
private fun DrawScope.drawBars(
animatedHeights: List<Animatable<Float, AnimationVector1D>>,
dataSource: List<ChartData>,
barWidth: Float,
barSpace: Float,
barColor: Color,
textMeasurer: TextMeasurer,
formatter: (Float) -> String
) {
animatedHeights.forEachIndexed { index, item ->
val barHeight = item.value * size.height
val offsetX = index * (barWidth + barSpace) + barSpace / 2
val offsetY = size.height - barHeight
// 绘制柱子
drawRect(
color = dataSource[index].color ?: barColor,
topLeft = Offset(offsetX, offsetY),
size = Size(barWidth, barHeight)
)
// 绘制数值
if (barWidth >= 10.dp.toPx()) {
drawValueLabel(
value = dataSource[index].value,
offsetX,
offsetY,
barWidth,
textMeasurer,
formatter,
barColor
)
}
}
}
private fun DrawScope.drawValueLabel(
value: Float,
offsetX: Float,
offsetY: Float,
barWidth: Float,
textMeasurer: TextMeasurer,
valueFormatter: (Float) -> String,
textColor: Color
) {
val valueText = valueFormatter(value)
val textLayoutResult = textMeasurer.measure(
valueText,
TextStyle(fontSize = 10.sp, fontWeight = FontWeight.Bold)
)
drawText(
textLayoutResult,
textColor,
Offset(
offsetX + barWidth / 2 - textLayoutResult.size.width / 2,
offsetY - textLayoutResult.size.height - 5.dp.toPx()
)
)
}
internal fun DrawScope.drawXAxis(
labels: List<String>,
barWidth: Float,
spaceWidth: Float,
axisColor: Color,
labelColor: Color,
textMeasurer: TextMeasurer
) {
// 绘制X轴
drawLine(
axisColor,
Offset(x = 0f, size.height),
Offset(x = size.width, size.height),
strokeWidth = 1.5.dp.toPx()
)
// 最后一个刻度的结束位置,初始化为负值表示还未开始绘制
var lastLabelEndX = -Float.MAX_VALUE
// 刻度之间的最小间隔
val labelPadding = 4.dp.toPx()
labels.forEachIndexed { index, label ->
val textLayoutResult = textMeasurer.measure(
label,
TextStyle(fontSize = 10.sp, fontWeight = FontWeight.Bold)
)
// 计算当前刻度的起始和结束位置
val labelStartX = index * (barWidth + spaceWidth) + spaceWidth / 2 +
barWidth / 2 - textLayoutResult.size.width / 2
val labelEndX = labelStartX + textLayoutResult.size.width
// 仅当当前刻度不与上一个刻度重叠时才绘制
if (labelStartX >= lastLabelEndX + labelPadding) {
drawText(
textLayoutResult,
labelColor,
topLeft = Offset(
x = labelStartX,
y = size.height + 10.dp.toPx()
)
)
// 更新最后一个刻度的结束位置
lastLabelEndX = labelEndX
}
}
} |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/navigation/ChartsGraph.kt | 2593980225 | package top.chengdongqing.weui.feature.charts.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import top.chengdongqing.weui.feature.charts.screens.BarChartScreen
import top.chengdongqing.weui.feature.charts.screens.LineChartScreen
import top.chengdongqing.weui.feature.charts.screens.PieChartScreen
fun NavGraphBuilder.addChartGraph() {
composable("bar_chart") {
BarChartScreen()
}
composable("line_chart") {
LineChartScreen()
}
composable("pie_chart") {
PieChartScreen()
}
} |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/utils/ColorUtils.kt | 1448241691 | package top.chengdongqing.weui.feature.charts.utils
import androidx.compose.ui.graphics.Color
/**
* 生成不重复的随机颜色
* @param count 需要的颜色数量
*/
fun generateColors(count: Int): List<Color> {
return List(count) { i ->
// 在360度色相环上均匀分布颜色
val hue = (360 * i / count) % 360
// 使用HSV色彩空间转换为Color
Color.hsv(hue.toFloat(), 0.85f, 0.85f)
}
}
|
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/screens/BarChart.kt | 3868194179 | package top.chengdongqing.weui.feature.charts.screens
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.theme.PrimaryColor
import top.chengdongqing.weui.core.ui.theme.WarningColor
import top.chengdongqing.weui.core.utils.format
import top.chengdongqing.weui.core.utils.randomFloat
import top.chengdongqing.weui.core.utils.rememberToggleState
import top.chengdongqing.weui.feature.charts.WeBarChart
import top.chengdongqing.weui.feature.charts.model.ChartData
@Composable
fun BarChartScreen() {
WeScreen(
title = "BarChart",
description = "柱状图",
containerColor = MaterialTheme.colorScheme.surface,
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
var dataSource by rememberSaveable { mutableStateOf(buildData()) }
val (color, toggleColor) = rememberToggleState(
defaultValue = PrimaryColor.copy(0.8f),
reverseValue = WarningColor.copy(0.8f)
)
val (maxBarWidth, toggleMaxBarWidth) = rememberToggleState(
defaultValue = 20,
reverseValue = 30
)
var scrollable by remember { mutableStateOf(false) }
Box(
modifier = if (scrollable) {
Modifier.horizontalScroll(rememberScrollState())
} else {
Modifier
}
) {
WeBarChart(
dataSource,
color = color.value,
barWidthRange = 2..maxBarWidth.value,
modifier = if (scrollable) {
Modifier.width((LocalConfiguration.current.screenWidthDp * 3).dp)
} else {
Modifier
}
) {
"¥" + it.format()
}
}
Spacer(modifier = Modifier.height(40.dp))
WeButton(text = "更新数据") {
dataSource = buildData(if (scrollable) 24 else 6)
}
WeButton(text = "切换颜色", type = ButtonType.DANGER) {
toggleColor()
}
WeButton(text = "切换横向滚动", type = ButtonType.PLAIN) {
dataSource = buildData(if (scrollable) 6 else 24)
scrollable = !scrollable
}
WeButton(text = "切换最大柱宽", type = ButtonType.PLAIN) {
toggleMaxBarWidth()
}
}
}
private fun buildData(size: Int = 6): List<ChartData> {
return MutableList(size) { index ->
val value = randomFloat(0f, 10000f)
ChartData(value, "${index + 1}月")
}
} |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/screens/PieChart.kt | 2611551232 | package top.chengdongqing.weui.feature.charts.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.utils.format
import top.chengdongqing.weui.core.utils.randomInt
import top.chengdongqing.weui.core.utils.rememberToggleState
import top.chengdongqing.weui.feature.charts.WePieChart
import top.chengdongqing.weui.feature.charts.model.ChartData
@Composable
fun PieChartScreen() {
WeScreen(
title = "PieChart",
description = "饼图",
containerColor = MaterialTheme.colorScheme.surface,
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
var dataSource by rememberSaveable { mutableStateOf(buildData()) }
val (ringWidth, toggleRingWidth) = rememberToggleState(
defaultValue = 0.dp,
reverseValue = 30.dp
)
WePieChart(dataSource, ringWidth.value) {
it.format() + "个"
}
WeButton(text = "更新数据") {
dataSource = buildData()
}
WeButton(text = "切换类型", type = ButtonType.PLAIN) {
toggleRingWidth()
}
}
}
private fun buildData(): List<ChartData> {
val allFruits = listOf("苹果", "香蕉", "樱桃", "西瓜", "草莓")
return allFruits.map { ChartData(randomInt(1, 100).toFloat(), it) }
} |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/screens/LineChart.kt | 23320536 | package top.chengdongqing.weui.feature.charts.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.theme.PrimaryColor
import top.chengdongqing.weui.core.ui.theme.WarningColor
import top.chengdongqing.weui.core.utils.format
import top.chengdongqing.weui.core.utils.randomFloat
import top.chengdongqing.weui.feature.charts.WeLineChart
import top.chengdongqing.weui.feature.charts.model.ChartData
import top.chengdongqing.weui.feature.charts.model.LineChartData
@Composable
fun LineChartScreen() {
WeScreen(
title = "LineChart",
description = "折线图",
containerColor = MaterialTheme.colorScheme.surface,
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
var dataSource by rememberSaveable {
mutableStateOf(
listOf(
LineChartData(
buildData(6),
PrimaryColor.copy(0.8f)
)
)
)
}
WeLineChart(
dataSources = dataSource
) {
"¥" + it.format()
}
Spacer(modifier = Modifier.height(40.dp))
WeButton(text = "更新数据") {
dataSource = buildList {
add(
LineChartData(
buildData(),
PrimaryColor.copy(0.8f)
)
)
if (dataSource.size == 2) {
add(
LineChartData(
buildData(),
WarningColor.copy(0.8f)
)
)
}
}
}
WeButton(text = "切换数量", type = ButtonType.PLAIN) {
dataSource = buildList {
add(
LineChartData(
buildData(),
PrimaryColor.copy(0.8f)
)
)
if (dataSource.size == 1) {
add(
LineChartData(
buildData(),
WarningColor.copy(0.8f)
)
)
}
}
}
}
}
private fun buildData(size: Int = 6): List<ChartData> {
return MutableList(size) { index ->
val value = randomFloat(0f, 10000f)
ChartData(value, "${index + 1}月")
}
} |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/PieChart.kt | 203816875 | package top.chengdongqing.weui.feature.charts
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.utils.format
import top.chengdongqing.weui.core.utils.generateColors
import top.chengdongqing.weui.feature.charts.model.ChartData
@Composable
fun WePieChart(
dataSource: List<ChartData>,
ringWidth: Dp = 0.dp,
animationSpec: AnimationSpec<Float> = tween(durationMillis = 800),
formatter: (Float) -> String = { it.format() }
) {
// 数值之和
val total = remember(dataSource) { dataSource.sumOf { it.value.toDouble() }.toFloat() }
// 随机颜色
val colors = remember(dataSource.size) { generateColors(dataSource.size) }
// 每个数据项的动画实例
val animatedSweepAngles = remember(dataSource.size) { dataSource.map { Animatable(0f) } }
LaunchedEffect(dataSource) {
// 累计角度,用于计算每个动画的起始角度
var accumulatedAngle = 0f
dataSource.forEachIndexed { index, item ->
// 当前扇形的夹角度数
val targetAngle = item.value / total * 360f
// 当前扇形的结束角度
val endAngle = accumulatedAngle + targetAngle
launch {
animatedSweepAngles[index].animateTo(
targetValue = endAngle,
animationSpec = animationSpec
)
}
// 更新累计角度为下一个扇形计算起始角度
accumulatedAngle += targetAngle
}
}
Row(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceAround
) {
ChartLegends(dataSource, colors, formatter)
PieFace(animatedSweepAngles, dataSource, colors, ringWidth)
}
}
@Composable
private fun PieFace(
animatedSweepAngles: List<Animatable<Float, AnimationVector1D>>,
dataSource: List<ChartData>,
colors: List<Color>,
ringWidth: Dp
) {
Canvas(
modifier = Modifier
.fillMaxWidth(0.6f)
.aspectRatio(1f)
) {
val innerRadius = if (ringWidth > 0.dp) {
ringWidth.toPx() / 2f
} else {
0f
}
var startAngle = -90f
animatedSweepAngles.forEachIndexed { index, item ->
val sweepAngle =
item.value - (if (index > 0) animatedSweepAngles[index - 1].value else 0f)
if (innerRadius > 0f) {
// 绘制环形图
drawArc(
color = dataSource[index].color ?: colors[index],
startAngle = startAngle,
sweepAngle = sweepAngle,
useCenter = false,
topLeft = Offset(innerRadius, innerRadius),
size = Size(size.width - 2 * innerRadius, size.height - 2 * innerRadius),
style = Stroke(width = ringWidth.toPx())
)
} else {
// 绘制饼图
drawArc(
color = dataSource[index].color ?: colors[index],
startAngle = startAngle,
sweepAngle = sweepAngle,
useCenter = true,
topLeft = Offset.Zero,
size = size
)
}
startAngle += sweepAngle
}
}
}
@Composable
private fun ChartLegends(
dataSource: List<ChartData>,
colors: List<Color>,
formatter: (Float) -> String
) {
Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
dataSource.forEachIndexed { index, item ->
Column {
Row(verticalAlignment = Alignment.CenterVertically) {
Box(
modifier = Modifier
.size(10.dp)
.background(item.color ?: colors[index], CircleShape)
)
Text(
text = item.label,
color = MaterialTheme.colorScheme.onPrimary,
fontSize = 12.sp,
lineHeight = 18.sp,
modifier = Modifier.padding(start = 4.dp)
)
}
Text(
text = formatter(item.value),
color = MaterialTheme.colorScheme.onSecondary,
fontSize = 11.sp,
lineHeight = 14.sp,
modifier = Modifier.padding(start = 14.dp)
)
}
}
}
} |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/model/ChartData.kt | 2673119130 | package top.chengdongqing.weui.feature.charts.model
import androidx.compose.ui.graphics.Color
data class ChartData(
val value: Float,
val label: String,
val color: Color? = null
) |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/model/LineChartData.kt | 2915152287 | package top.chengdongqing.weui.feature.charts.model
import androidx.compose.ui.graphics.Color
data class LineChartData(val points: List<ChartData>, val color: Color) |
WeUI/feature/charts/src/main/kotlin/top/chengdongqing/weui/feature/charts/LineChart.kt | 698325444 | package top.chengdongqing.weui.feature.charts
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationSpec
import androidx.compose.animation.core.AnimationVector1D
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.utils.format
import top.chengdongqing.weui.feature.charts.model.ChartData
import top.chengdongqing.weui.feature.charts.model.LineChartData
@Composable
fun WeLineChart(
dataSources: List<LineChartData>,
height: Dp = 300.dp,
color: Color = MaterialTheme.colorScheme.primary.copy(0.8f),
animationSpec: AnimationSpec<Float> = tween(durationMillis = 800),
formatter: (Float) -> String = { it.format() }
) {
val textMeasurer = rememberTextMeasurer()
val labelColor = MaterialTheme.colorScheme.onSecondary
val containerColor = MaterialTheme.colorScheme.onBackground
// 计算所有数据源中的最大值
val maxValue = remember(dataSources) {
dataSources.flatMap { it.points }.maxOfOrNull { it.value } ?: 1f
}
// 为每个数据点创建动画实例
val animatedValuesList = remember(dataSources.size) {
dataSources.map { dataSource ->
dataSource.points.map { Animatable(0f) }
}
}
// 数据变化后执行动画
LaunchedEffect(dataSources) {
animatedValuesList.forEachIndexed { dataSourceIndex, animatedValues ->
animatedValues.forEachIndexed { index, item ->
launch {
item.animateTo(
targetValue = dataSources[dataSourceIndex].points[index].value / maxValue,
animationSpec = animationSpec
)
}
}
}
}
Canvas(
modifier = Modifier
.fillMaxWidth()
.padding(top = 20.dp)
.height(height)
) {
// 使用第一个数据源的标签
val labels = dataSources.firstOrNull()?.points?.map { it.label } ?: emptyList()
// 绘制X轴
drawXAxis(
labels = labels,
size.width / labels.size,
0f,
axisColor = color,
labelColor,
textMeasurer
)
// 为每个数据源绘制折线和数据点
dataSources.forEachIndexed { index, dataSource ->
drawLines(
animatedValuesList[index],
dataSource.points,
lineColor = dataSource.color,
containerColor = containerColor,
textMeasurer,
formatter
)
}
}
}
private fun DrawScope.drawLines(
animatedValues: List<Animatable<Float, AnimationVector1D>>,
dataSource: List<ChartData>,
lineColor: Color,
containerColor: Color,
textMeasurer: TextMeasurer,
formatter: (Float) -> String
) {
val pointWidth = 1.5.dp.toPx()
val pointSpace = (size.width - pointWidth * dataSource.size) / dataSource.size
animatedValues.draw(pointWidth, pointSpace, size.height) { currentPoint, previousPoint, index ->
// 绘制数值标签
if (pointSpace >= 10.dp.toPx()) {
drawValueLabel(
value = dataSource[index].value,
currentPoint.x,
currentPoint.y,
textMeasurer,
formatter,
lineColor
)
}
// 连接数据点
previousPoint?.let {
drawLine(
color = lineColor,
start = it,
end = currentPoint,
strokeWidth = pointWidth
)
}
}
// 绘制数据点
animatedValues.draw(pointWidth, pointSpace, size.height) { currentPoint, _, _ ->
drawCircle(color = lineColor, radius = 3.dp.toPx(), center = currentPoint)
drawCircle(color = containerColor, radius = 1.5.dp.toPx(), center = currentPoint)
}
}
private fun List<Animatable<Float, AnimationVector1D>>.draw(
pointWidth: Float,
pointSpace: Float,
height: Float,
block: (currentPoint: Offset, previousPoint: Offset?, index: Int) -> Unit
) {
var previousPoint: Offset? = null
this.forEachIndexed { index, item ->
val x = index * (pointWidth + pointSpace) + pointSpace / 2
val y = height - (item.value * height)
val currentPoint = Offset(x, y)
block(currentPoint, previousPoint, index)
previousPoint = currentPoint
}
}
private fun DrawScope.drawValueLabel(
value: Float,
offsetX: Float,
offsetY: Float,
textMeasurer: TextMeasurer,
valueFormatter: (Float) -> String,
textColor: Color
) {
val valueText = valueFormatter(value)
val textLayoutResult = textMeasurer.measure(
valueText,
TextStyle(fontSize = 10.sp, fontWeight = FontWeight.Bold)
)
drawText(
textLayoutResult,
textColor,
Offset(
offsetX - textLayoutResult.size.width / 2,
offsetY - textLayoutResult.size.height - 5.dp.toPx()
)
)
} |
WeUI/feature/feedback/src/androidTest/java/top/chengdongqing/weui/feature/feedback/ExampleInstrumentedTest.kt | 3127543715 | package top.chengdongqing.weui.feature.feedback
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("top.chengdongqing.weui.feature.feedback.test", appContext.packageName)
}
} |
WeUI/feature/feedback/src/test/java/top/chengdongqing/weui/feature/feedback/ExampleUnitTest.kt | 4218313014 | package top.chengdongqing.weui.feature.feedback
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
WeUI/feature/feedback/src/main/kotlin/top/chengdongqing/weui/feature/feedback/navigation/FeedbackGraph.kt | 1639459255 | package top.chengdongqing.weui.feature.feedback.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import top.chengdongqing.weui.feature.feedback.screens.ActionSheetScreen
import top.chengdongqing.weui.feature.feedback.screens.ContextMenuScreen
import top.chengdongqing.weui.feature.feedback.screens.DialogScreen
import top.chengdongqing.weui.feature.feedback.screens.InformationBarScreen
import top.chengdongqing.weui.feature.feedback.screens.PopupScreen
import top.chengdongqing.weui.feature.feedback.screens.ToastScreen
fun NavGraphBuilder.addFeedbackGraph() {
composable("dialog") {
DialogScreen()
}
composable("popup") {
PopupScreen()
}
composable("action_sheet") {
ActionSheetScreen()
}
composable("toast") {
ToastScreen()
}
composable("information_bar") {
InformationBarScreen()
}
composable("context_menu") {
ContextMenuScreen()
}
} |
WeUI/feature/feedback/src/main/kotlin/top/chengdongqing/weui/feature/feedback/screens/Toast.kt | 3730571436 | package top.chengdongqing.weui.feature.feedback.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.toast.ToastIcon
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
import kotlin.time.Duration
@Composable
fun ToastScreen() {
val toast = rememberToastState()
val coroutineScope = rememberCoroutineScope()
WeScreen(
title = "Toast",
description = "弹出式提示",
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
WeButton(text = "成功提示", type = ButtonType.PLAIN) {
toast.show(title = "已完成", icon = ToastIcon.SUCCESS)
}
WeButton(text = "失败提示", type = ButtonType.PLAIN) {
toast.show(title = "获取链接失败", icon = ToastIcon.FAIL)
}
WeButton(text = "长文案提示", type = ButtonType.PLAIN) {
toast.show(title = "此处为长文案提示详情", icon = ToastIcon.FAIL)
}
WeButton(text = "立即支付", type = ButtonType.PLAIN) {
toast.show(
title = "支付中...",
icon = ToastIcon.LOADING,
duration = Duration.INFINITE,
mask = true
)
coroutineScope.launch {
delay(2000)
toast.hide()
delay(200)
toast.show(title = "支付成功", icon = ToastIcon.SUCCESS)
}
}
WeButton(text = "文字提示", type = ButtonType.PLAIN) {
toast.show("文字提示")
}
}
} |
WeUI/feature/feedback/src/main/kotlin/top/chengdongqing/weui/feature/feedback/screens/ContextMenu.kt | 2049348915 | package top.chengdongqing.weui.feature.feedback.screens
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem
import top.chengdongqing.weui.core.ui.components.cardlist.cartList
import top.chengdongqing.weui.core.ui.components.contextmenu.contextMenu
import top.chengdongqing.weui.core.ui.components.contextmenu.rememberContextMenuState
import top.chengdongqing.weui.core.ui.components.dialog.rememberDialogState
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
@Composable
fun ContextMenuScreen() {
WeScreen(
title = "ContextMenu",
description = "上下文菜单",
scrollEnabled = false
) {
val menus = remember {
listOf("标为未读", "置顶该聊天", "不显示该聊天", "删除该聊天")
}
val dialog = rememberDialogState()
val contextMenuState = rememberContextMenuState { listIndex, menuIndex ->
dialog.show(
title = "你点击了第${listIndex + 1}项的“${menus[menuIndex]}”",
onCancel = null
)
}
LazyColumn(modifier = Modifier.cartList()) {
items(30) { index ->
Box(
modifier = Modifier
.contextMenu { position ->
contextMenuState.show(position, menus, index)
}
) {
WeCardListItem(label = "第${index + 1}项")
}
}
}
}
} |
WeUI/feature/feedback/src/main/kotlin/top/chengdongqing/weui/feature/feedback/screens/InformationBar.kt | 2166438733 | package top.chengdongqing.weui.feature.feedback.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.ButtonSize
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.informationbar.InformationBarType
import top.chengdongqing.weui.core.ui.components.informationbar.WeInformationBar
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
@Composable
fun InformationBarScreen() {
WeScreen(
title = "InformationBar",
description = "信息提示条",
horizontalAlignment = Alignment.End,
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
val (visible, setVisible) = remember { mutableStateOf(true) }
WeInformationBar(
visible = visible,
content = "成功提示 success",
type = InformationBarType.SUCCESS,
linkText = "详情"
) {
setVisible(false)
}
if (!visible) {
WeButton(text = "显示", type = ButtonType.PLAIN, size = ButtonSize.SMALL) {
setVisible(true)
}
}
WeInformationBar(
content = "信息提示 warn strong",
type = InformationBarType.WARN_STRONG
)
WeInformationBar(content = "信息提示 info", type = InformationBarType.INFO)
WeInformationBar(
content = "信息提示 tips strong",
type = InformationBarType.TIPS_STRONG
)
WeInformationBar(content = "信息提示 tips weak", type = InformationBarType.TIPS_WEAK)
}
} |
WeUI/feature/feedback/src/main/kotlin/top/chengdongqing/weui/feature/feedback/screens/Dialog.kt | 1207715612 | package top.chengdongqing.weui.feature.feedback.screens
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.dialog.rememberDialogState
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
@Composable
fun DialogScreen() {
WeScreen(title = "Dialog", description = "对话框") {
val dialog = rememberDialogState()
WeButton(text = "Dialog 样式一", type = ButtonType.PLAIN) {
dialog.show(
title = "弹窗标题",
content = "弹窗内容,告知当前状态、信息和解决方法,描述文字尽量控制在三行内",
okText = "主操作",
cancelText = "辅助操作"
)
}
Spacer(Modifier.height(16.dp))
WeButton(text = "Dialog 样式二", type = ButtonType.PLAIN) {
dialog.show(
title = "弹窗内容,告知当前状态、信息和解决方法,描述文字尽量控制在三行内",
okText = "知道了",
onCancel = null
)
}
}
} |
WeUI/feature/feedback/src/main/kotlin/top/chengdongqing/weui/feature/feedback/screens/Popup.kt | 202656587 | package top.chengdongqing.weui.feature.feedback.screens
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.popup.WePopup
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
@Composable
fun PopupScreen() {
WeScreen(title = "Popup", description = "弹出框") {
var visible by remember { mutableStateOf(false) }
var draggable by remember { mutableStateOf(false) }
WePopup(
visible,
title = "标题",
draggable = draggable,
onClose = { visible = false }
) {
Text(text = "内容", color = MaterialTheme.colorScheme.onPrimary)
Spacer(modifier = Modifier.height(200.dp))
}
WeButton(text = "样式一", type = ButtonType.PLAIN) {
draggable = false
visible = true
}
Spacer(modifier = Modifier.height(20.dp))
WeButton(text = "样式二", type = ButtonType.PLAIN) {
draggable = true
visible = true
}
}
} |
WeUI/feature/feedback/src/main/kotlin/top/chengdongqing/weui/feature/feedback/screens/ActionSheet.kt | 593382161 | package top.chengdongqing.weui.feature.feedback.screens
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Call
import androidx.compose.material.icons.filled.Videocam
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.data.model.VisualMediaType
import top.chengdongqing.weui.core.ui.components.actionsheet.ActionSheetItem
import top.chengdongqing.weui.core.ui.components.actionsheet.rememberActionSheetState
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.camera.rememberCameraLauncher
import top.chengdongqing.weui.core.ui.components.mediapicker.rememberPickMediasLauncher
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.toast.ToastIcon
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
import top.chengdongqing.weui.core.ui.theme.PrimaryColor
@Composable
fun ActionSheetScreen() {
WeScreen(title = "ActionSheet", description = "弹出式菜单") {
MakeCall()
Spacer(modifier = Modifier.height(20.dp))
RequestPay()
Spacer(modifier = Modifier.height(20.dp))
ShareToTimeline()
}
}
@Composable
private fun RequestPay() {
val actionSheet = rememberActionSheetState()
val toast = rememberToastState()
val options = remember {
listOf(
ActionSheetItem("微信", color = PrimaryColor),
ActionSheetItem("支付宝", color = Color(0xFF00BBEE)),
ActionSheetItem("QQ钱包", color = Color.Red),
ActionSheetItem("小米钱包", "禁用", disabled = true)
)
}
WeButton(text = "立即支付", type = ButtonType.DANGER) {
actionSheet.show(options, "请选择支付方式") {
toast.show("点击了第${it + 1}个")
}
}
}
@Composable
private fun MakeCall() {
val actionSheet = rememberActionSheetState()
val toast = rememberToastState()
val options = remember {
listOf(
ActionSheetItem("视频通话", icon = {
Icon(
imageVector = Icons.Filled.Videocam,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.size(22.dp)
)
}),
ActionSheetItem("语音通话", icon = {
Icon(
imageVector = Icons.Filled.Call,
contentDescription = null,
tint = MaterialTheme.colorScheme.onPrimary,
modifier = Modifier.size(18.dp)
)
})
)
}
WeButton(text = "开始通话", type = ButtonType.PLAIN) {
actionSheet.show(options) {
toast.show("开始${options[it].label}")
}
}
}
@Composable
private fun ShareToTimeline() {
val toast = rememberToastState()
val launchCamera = rememberCameraLauncher { _, _ ->
toast.show("发布成功", ToastIcon.SUCCESS)
}
val pickMedia = rememberPickMediasLauncher {
toast.show("发布成功", ToastIcon.SUCCESS)
}
val actionSheet = rememberActionSheetState()
val options = remember {
listOf(
ActionSheetItem("拍摄", "照片或视频"),
ActionSheetItem("从相册选择")
)
}
WeButton(text = "发朋友圈") {
actionSheet.show(options) {
when (it) {
0 -> launchCamera(VisualMediaType.IMAGE_AND_VIDEO)
1 -> pickMedia(VisualMediaType.IMAGE_AND_VIDEO, 9)
}
}
}
} |
WeUI/feature/qrcode/src/androidTest/java/top/chengdongqing/weui/feature/qrcode/ExampleInstrumentedTest.kt | 2796495938 | package top.chengdongqing.weui.feature.qrcode
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("top.chengdongqing.weui.feature.qrcode.test", appContext.packageName)
}
} |
WeUI/feature/qrcode/src/test/java/top/chengdongqing/weui/feature/qrcode/ExampleUnitTest.kt | 2873045441 | package top.chengdongqing.weui.feature.qrcode
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/navigation/QrCodeGraph.kt | 1965092602 | package top.chengdongqing.weui.feature.qrcode.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import top.chengdongqing.weui.feature.qrcode.screens.QrCodeGeneratorScreen
import top.chengdongqing.weui.feature.qrcode.screens.QrCodeScanScreen
fun NavGraphBuilder.addQrCodeGraph() {
composable("qrcode_scanner") {
QrCodeScanScreen()
}
composable("qrcode_generator") {
QrCodeGeneratorScreen()
}
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/screens/QrCodeGenerator.kt | 2987726177 | package top.chengdongqing.weui.feature.qrcode.screens
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.ButtonType
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.input.WeTextarea
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.core.ui.components.toast.ToastIcon
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
import top.chengdongqing.weui.feature.qrcode.generator.WeQrCodeGenerator
import kotlin.math.roundToInt
@Composable
fun QrCodeGeneratorScreen() {
WeScreen(title = "QrCodeGenerator", description = "二维码生成") {
var content by remember { mutableStateOf("https://weui.io") }
var finalContent by remember { mutableStateOf("") }
val size = rememberScreenWidth()
val toast = rememberToastState()
WeTextarea(value = content, placeholder = "请输入内容", topBorder = true) {
content = it
}
Spacer(modifier = Modifier.height(20.dp))
WeButton(text = "生成二维码", type = ButtonType.PLAIN) {
if (content.isNotEmpty()) {
finalContent = content
} else {
toast.show("请输入内容", ToastIcon.FAIL)
}
}
Spacer(modifier = Modifier.height(60.dp))
if (finalContent.isNotEmpty()) {
WeQrCodeGenerator(
content = finalContent,
size = size,
color = MaterialTheme.colorScheme.onPrimary
)
}
}
}
@Composable
private fun rememberScreenWidth(fraction: Float = 0.6f): Int {
val density = LocalDensity.current
val configuration = LocalConfiguration.current
return remember {
with(density) {
(configuration.screenWidthDp * fraction).dp.toPx().roundToInt()
}
}
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/screens/QrCodeScanner.kt | 876873971 | package top.chengdongqing.weui.feature.qrcode.screens
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import top.chengdongqing.weui.core.ui.components.button.WeButton
import top.chengdongqing.weui.core.ui.components.input.WeTextarea
import top.chengdongqing.weui.core.ui.components.screen.WeScreen
import top.chengdongqing.weui.feature.qrcode.scanner.rememberScanCodeLauncher
@Composable
fun QrCodeScanScreen() {
WeScreen(title = "QrCodeScanner", description = "扫码") {
var value by remember { mutableStateOf<String?>(null) }
val scanCode = rememberScanCodeLauncher {
value = it.joinToString("\n")
}
value?.let {
WeTextarea(it, label = "扫码结果")
Spacer(modifier = Modifier.height(40.dp))
}
WeButton(text = "扫一扫") {
scanCode()
}
}
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/generator/QrCodeGenerator.kt | 732823363 | package top.chengdongqing.weui.feature.qrcode.generator
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.runtime.Composable
import androidx.compose.runtime.produceState
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.toArgb
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.qrcode.QRCodeWriter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import android.graphics.Color as AndroidColor
@Composable
fun WeQrCodeGenerator(content: String, size: Int, color: Color = Color.Black) {
val bitmap = produceState<ImageBitmap?>(initialValue = null, key1 = content, key2 = size) {
value = withContext(Dispatchers.IO) {
generateQrCode(content, size, color.toArgb()).asImageBitmap()
}
}
bitmap.value?.let {
Image(bitmap = it, contentDescription = "二维码")
}
}
private fun generateQrCode(content: String, size: Int, color: Int): Bitmap {
val hints = mapOf(EncodeHintType.MARGIN to 0)
val bitMatrix = QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, size, size, hints)
val pixels = IntArray(size * size) { pos ->
if (bitMatrix.get(pos % size, pos / size)) {
color
} else {
AndroidColor.TRANSPARENT
}
}
return Bitmap.createBitmap(pixels, size, size, Bitmap.Config.ARGB_8888)
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/scanner/ScannerState.kt | 2842537615 | package top.chengdongqing.weui.feature.qrcode.scanner
import android.content.Context
import android.net.Uri
import android.view.ViewGroup
import androidx.camera.core.Camera
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.LifecycleOwner
import com.google.mlkit.vision.barcode.common.Barcode
import top.chengdongqing.weui.core.utils.rememberSingleThreadExecutor
import java.util.concurrent.ExecutorService
@Stable
interface ScannerState {
/**
* 相机预览视图
*/
val previewView: PreviewView
/**
* 是否开启闪光灯
*/
val isFlashOn: Boolean
/**
* 更新相机
*/
fun updateCamera()
/**
* 切换闪光灯状态
*/
fun toggleFlashState()
/**
* 扫描指定图片
*/
fun scanPhoto(uri: Uri, onFail: () -> Unit)
}
@Composable
fun rememberScannerState(onChange: (List<Barcode>) -> Unit): ScannerState {
val context = LocalContext.current
val lifecycleOwner = LocalLifecycleOwner.current
val executor = rememberSingleThreadExecutor()
return remember {
ScannerStateImpl(context, lifecycleOwner, executor, onChange)
}
}
private class ScannerStateImpl(
private val context: Context,
private val lifecycleOwner: LifecycleOwner,
private val executor: ExecutorService,
private val onChange: (List<Barcode>) -> Unit
) : ScannerState {
override val previewView = PreviewView(context).apply {
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
keepScreenOn = true
}
override var isFlashOn by mutableStateOf(false)
override fun updateCamera() {
val cameraProviderFuture = ProcessCameraProvider.getInstance(context)
val cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(previewView.surfaceProvider)
}
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
val barcodeAnalyzer = BarcodeAnalyzer { barcodes ->
if (barcodes.isNotEmpty()) {
onChange(barcodes)
}
}
val imageAnalysis = ImageAnalysis.Builder()
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.build().apply { setAnalyzer(executor, barcodeAnalyzer) }
try {
cameraProvider.unbindAll()
camera = cameraProvider.bindToLifecycle(
lifecycleOwner,
cameraSelector,
preview,
imageAnalysis
)
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun toggleFlashState() {
isFlashOn = !isFlashOn
camera?.let {
if (it.cameraInfo.hasFlashUnit()) {
it.cameraControl.enableTorch(isFlashOn)
}
}
}
override fun scanPhoto(uri: Uri, onFail: () -> Unit) {
decodeBarcodeFromUri(context, uri) { barcodes ->
if (barcodes.isNotEmpty()) {
onChange(barcodes)
} else {
onFail()
}
}
}
private var camera: Camera? = null
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/scanner/QrCodeScannerActivity.kt | 1415618571 | package top.chengdongqing.weui.feature.qrcode.scanner
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import top.chengdongqing.weui.core.ui.theme.WeUITheme
class QrCodeScannerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WeUITheme {
WeQrCodeScanner(
onRevoked = { finish() }
) { codes ->
val intent = Intent().apply {
putExtra("codes", codes.map { it.rawValue }.toTypedArray())
}
setResult(RESULT_OK, intent)
finish()
}
}
}
}
companion object {
fun newIntent(context: Context) = Intent(context, QrCodeScannerActivity::class.java)
}
}
@Composable
fun rememberScanCodeLauncher(onChange: (Array<String>) -> Unit): () -> Unit {
val context = LocalContext.current
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
result.data?.getStringArrayExtra("codes")?.let(onChange)
}
}
return {
launcher.launch(QrCodeScannerActivity.newIntent(context))
}
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/scanner/ScannerDecoration.kt | 4116865455 | package top.chengdongqing.weui.feature.qrcode.scanner
import androidx.compose.animation.core.InfiniteRepeatableSpec
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.RepeatMode
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
internal fun BoxScope.ScannerDecoration() {
ScanningAnimation()
Text(
text = "扫二维码 / 条码",
color = Color.White,
fontSize = 16.sp,
modifier = Modifier
.align(Alignment.BottomCenter)
.offset(y = (-150).dp)
)
}
@Composable
private fun BoxScope.ScanningAnimation() {
val screenHeight = LocalConfiguration.current.screenHeightDp
val transition = rememberInfiniteTransition(label = "")
val offsetY by transition.animateFloat(
initialValue = 0.2f,
targetValue = 0.7f,
animationSpec = InfiniteRepeatableSpec(
animation = tween(durationMillis = 3000, easing = LinearEasing),
repeatMode = RepeatMode.Restart
),
label = "QrCodeScanningAnimation"
)
Box(
modifier = Modifier
.offset(y = (offsetY * screenHeight).dp)
.align(Alignment.TopCenter)
.fillMaxWidth(0.8f)
.height(5.dp)
.background(
Brush.linearGradient(
colors = listOf(
Color.Transparent,
MaterialTheme.colorScheme.primary.copy(0.6f),
Color.Transparent
)
)
)
)
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/scanner/QrCodeScanner.kt | 222749451 | package top.chengdongqing.weui.feature.qrcode.scanner
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import com.google.mlkit.vision.barcode.common.Barcode
import top.chengdongqing.weui.core.utils.RequestCameraPermission
@Composable
fun WeQrCodeScanner(onRevoked: () -> Unit, onChange: (List<Barcode>) -> Unit) {
val state = rememberScannerState(onChange)
RequestCameraPermission(onRevoked = onRevoked) {
CameraView(state)
ScannerDecoration()
ScannerTools(state)
}
}
@Composable
private fun CameraView(state: ScannerState) {
AndroidView(
factory = { state.previewView },
modifier = Modifier.fillMaxSize(),
update = { state.updateCamera() }
)
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/scanner/BarcodeDecoder.kt | 2595507238 | package top.chengdongqing.weui.feature.qrcode.scanner
import android.content.Context
import android.net.Uri
import androidx.annotation.OptIn
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage
internal class BarcodeAnalyzer(
private val onChange: (List<Barcode>) -> Unit
) : ImageAnalysis.Analyzer {
@OptIn(ExperimentalGetImage::class)
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
val scanner = BarcodeScanning.getClient(
BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_ALL_FORMATS)
.build()
)
scanner.process(image)
.addOnSuccessListener { barcodes ->
onChange(barcodes)
}
.addOnFailureListener { e ->
e.printStackTrace()
}
.addOnCompleteListener {
imageProxy.close()
}
}
}
internal fun decodeBarcodeFromUri(context: Context, uri: Uri, onChange: (List<Barcode>) -> Unit) {
val image = InputImage.fromFilePath(context, uri)
val scanner = BarcodeScanning.getClient(
BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_ALL_FORMATS)
.build()
)
scanner.process(image)
.addOnSuccessListener { barcodes ->
onChange(barcodes)
}
.addOnFailureListener { e ->
e.printStackTrace()
}
} |
WeUI/feature/qrcode/src/main/kotlin/top/chengdongqing/weui/feature/qrcode/scanner/ScannerTools.kt | 688402261 | package top.chengdongqing.weui.feature.qrcode.scanner
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FlashlightOff
import androidx.compose.material.icons.filled.FlashlightOn
import androidx.compose.material.icons.filled.Image
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import top.chengdongqing.weui.core.data.model.VisualMediaType
import top.chengdongqing.weui.core.ui.components.mediapicker.rememberPickMediasLauncher
import top.chengdongqing.weui.core.ui.components.toast.ToastIcon
import top.chengdongqing.weui.core.ui.components.toast.rememberToastState
@Composable
internal fun BoxScope.ScannerTools(state: ScannerState) {
val toast = rememberToastState()
Row(
modifier = Modifier
.fillMaxWidth()
.align(Alignment.BottomCenter)
.padding(40.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
ToolItem(
label = "闪光灯",
icon = if (state.isFlashOn) Icons.Filled.FlashlightOn else Icons.Filled.FlashlightOff,
iconColor = if (state.isFlashOn) MaterialTheme.colorScheme.primary else Color.White
) {
state.toggleFlashState()
}
val pickMedia = rememberPickMediasLauncher {
state.scanPhoto(it.first().uri) {
toast.show("识别失败", ToastIcon.FAIL)
}
}
ToolItem(label = "相册", icon = Icons.Filled.Image) {
pickMedia(VisualMediaType.IMAGE, 1)
if (state.isFlashOn) {
state.toggleFlashState()
}
}
}
}
@Composable
private fun ToolItem(
label: String,
icon: ImageVector,
iconColor: Color = Color.White,
onClick: () -> Unit
) {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
Box(
modifier = Modifier
.clip(CircleShape)
.background(Color.White.copy(0.2f))
.clickable { onClick() }
.padding(12.dp)
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = iconColor,
modifier = Modifier.size(24.dp)
)
}
Spacer(modifier = Modifier.height(8.dp))
Text(text = label, color = Color.White, fontSize = 13.sp)
}
} |
WeUI/feature/samples/paint/src/androidTest/java/top/chengdongqing/weui/feature/demos/paint/ExampleInstrumentedTest.kt | 3266688996 | package top.chengdongqing.weui.feature.samples.paint
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("top.chengdongqing.weui.feature.samples.paint.test", appContext.packageName)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.