path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/HelperLayout.kt
1401251652
package com.theminesec.example.headless.exampleHelper import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.theminesec.example.headless.exampleHelper.component.ObjectDisplay import com.theminesec.example.headless.exampleHelper.component.SplitSection import com.theminesec.example.headless.exampleHelper.theme.MsExampleTheme @Composable fun HelperLayout( content: @Composable ColumnScope.() -> Unit, ) { MsExampleTheme { val viewModel: HelperViewModel = viewModel() val messages by viewModel.messages.collectAsState() val lazyListState = rememberLazyListState() val snackbarHostState = remember { SnackbarHostState() } val localFocusManager = LocalFocusManager.current // scroll to bottom when new message comes in LaunchedEffect(messages) { lazyListState.animateScrollToItem((messages.size - 1).coerceAtLeast(0)) } Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { Scaffold( modifier = Modifier.fillMaxSize(), snackbarHost = { SnackbarHost(snackbarHostState) } ) { padding -> Column( modifier = Modifier .fillMaxSize() .padding(padding) .pointerInput(Unit) { detectTapGestures(onTap = { localFocusManager.clearFocus() }) }, ) { SplitSection( upperContent = { Column( verticalArrangement = Arrangement.spacedBy(16.dp) ) { content() } }, lowerContent = { Box(modifier = Modifier.fillMaxSize()) { LazyColumn( state = lazyListState, modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues( start = 16.dp, top = 56.dp, end = 16.dp, bottom = 16.dp ) ) { items(messages) { msg -> ObjectDisplay(msg) } } Button( onClick = { viewModel.clearLog() }, modifier = Modifier .align(Alignment.TopEnd) .defaultMinSize(minHeight = 40.dp, minWidth = 64.dp) .padding(8.dp), colors = ButtonDefaults.outlinedButtonColors( containerColor = MaterialTheme.colorScheme.background.copy(0.6f), contentColor = Color.White.copy(0.8f) ), border = BorderStroke(1.dp, Color.White.copy(alpha = 0.4f)), shape = RoundedCornerShape(8.dp) ) { Text(text = "Clear") } } } ) } } } } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/theme/Theme.kt
1288871276
package com.theminesec.example.headless.exampleHelper.theme import android.app.Activity import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalView val ShamrockGreen = Color(0xff2BD659) val SlateGray = Color(0xff64748b) val CatalinaBlue = Color(0xff101A2D) @Composable fun MsExampleTheme(content: @Composable () -> Unit) { val colorScheme = darkColorScheme( primary = ShamrockGreen, onPrimary = CatalinaBlue, secondary = SlateGray, background = CatalinaBlue, onBackground = Color.White ) val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.background.toArgb() } } MaterialTheme( colorScheme = colorScheme, typography = Type, content = content ) }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/theme/Type.kt
3634738681
package com.theminesec.example.headless.exampleHelper.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.sp import com.theminesec.example.headless.R // Set of Material typography styles to start with private val jetBrainMono = FontFamily( Font(R.font.jbm_medium) ) private val defaultTypography = Typography() val Type = Typography( displayLarge = defaultTypography.displayLarge.copy(fontFamily = jetBrainMono), displayMedium = defaultTypography.displayMedium.copy(fontFamily = jetBrainMono), displaySmall = defaultTypography.displaySmall.copy(fontFamily = jetBrainMono), headlineLarge = defaultTypography.headlineLarge.copy(fontFamily = jetBrainMono), headlineMedium = defaultTypography.headlineMedium.copy(fontFamily = jetBrainMono), headlineSmall = defaultTypography.headlineSmall.copy(fontFamily = jetBrainMono), titleLarge = defaultTypography.titleLarge.copy(fontFamily = jetBrainMono), titleMedium = defaultTypography.titleMedium.copy(fontFamily = jetBrainMono), titleSmall = defaultTypography.titleSmall.copy(fontFamily = jetBrainMono), bodyLarge = defaultTypography.bodyLarge.copy(fontFamily = jetBrainMono, fontSize = 12.sp, lineHeight = 16.sp), bodyMedium = defaultTypography.bodyMedium.copy(fontFamily = jetBrainMono, fontSize = 12.sp, lineHeight = 16.sp), bodySmall = defaultTypography.bodySmall.copy(fontFamily = jetBrainMono, fontSize = 12.sp, lineHeight = 16.sp), labelLarge = defaultTypography.labelLarge.copy(fontFamily = jetBrainMono, fontSize = 12.sp), labelMedium = defaultTypography.labelMedium.copy(fontFamily = jetBrainMono, fontSize = 10.sp), labelSmall = defaultTypography.labelSmall.copy(fontFamily = jetBrainMono, fontSize = 10.sp, lineHeight = 12.sp), )
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/exampleHelper/HelperViewModel.kt
2864784091
package com.theminesec.example.headless.exampleHelper import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.theminesec.example.headless.util.TAG import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import ulid.ULID class HelperViewModel : ViewModel() { // for demo setups private val _messages: MutableStateFlow<List<String>> = MutableStateFlow(emptyList()) val messages: StateFlow<List<String>> = _messages fun writeMessage(message: String) = viewModelScope.launch { val temp = _messages.value .toMutableList() .apply { add("==> $message") } _messages.emit(temp) } fun clearLog() = viewModelScope.launch { _messages.emit(emptyList()) } // demo part var posReference by mutableStateOf(ULID.randomULID()) val currency by mutableStateOf("HKD") var amountStr by mutableStateOf("2") private set fun handleInputAmt(incomingStr: String) { Log.d(TAG, "incoming: $incomingStr") if (incomingStr.length > 12) return if (incomingStr.count { c -> c == '.' } > 1) return incomingStr.split(".").getOrNull(1)?.let { afterDecimal -> if (afterDecimal.length > 2) return } amountStr = incomingStr.filter { c -> c.isDigit() || c == '.' } } fun resetRandomPosReference() { posReference = ULID.randomULID() } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/ClientMain.kt
2697151192
package com.theminesec.example.headless import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.* import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Refresh import androidx.compose.material3.* import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.lifecycle.lifecycleScope import com.google.gson.* import com.theminesec.example.headless.exampleHelper.HelperLayout import com.theminesec.example.headless.exampleHelper.HelperViewModel import com.theminesec.example.headless.exampleHelper.component.Button import com.theminesec.sdk.headless.HeadlessActivity import com.theminesec.sdk.headless.HeadlessService import com.theminesec.sdk.headless.HeadlessSetup import com.theminesec.sdk.headless.model.WrappedResult import com.theminesec.sdk.headless.model.transaction.* import kotlinx.coroutines.launch import java.lang.reflect.Type import java.math.BigDecimal import java.time.Instant import java.util.* class ClientMain : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val viewModel: HelperViewModel by viewModels() var completedSaleTranId: String? by mutableStateOf(null) var completedSalePosReference: String? by mutableStateOf(null) var completedSaleRequestId: String? by mutableStateOf(null) var completedRefundTranId: String? by mutableStateOf(null) val gson = GsonBuilder() .registerTypeAdapter(Instant::class.java, object : JsonSerializer<Instant> { override fun serialize(p0: Instant?, p1: Type?, p2: JsonSerializationContext?): JsonElement = JsonPrimitive(p0?.toString()) }) .setPrettyPrinting().create() val launcher = registerForActivityResult( HeadlessActivity.contract(ClientHeadlessImpl::class.java) ) { viewModel.writeMessage("${it.javaClass.simpleName} \n${gson.toJson(it)}") viewModel.resetRandomPosReference() when (it) { is WrappedResult.Success -> { if (it.value.tranType == TranType.SALE) { completedSaleTranId = it.value.tranId completedSalePosReference = it.value.posReference completedSaleRequestId = it.value.actions.firstOrNull()?.requestId } if (it.value.tranType == TranType.REFUND) { completedRefundTranId = it.value.tranId } } is WrappedResult.Failure -> { viewModel.writeMessage("Failed") } } } setContent { HelperLayout { Button(onClick = { val sdkInitResp = (application as ClientApp).sdkInitResp viewModel.writeMessage("sdkInitResp: $sdkInitResp}") }) { Text(text = "SDK init status") } Button(onClick = { lifecycleScope.launch { val res = HeadlessSetup.initialSetup(this@ClientMain) viewModel.writeMessage("initialSetup: $res") } }) { Text(text = "Initial setups (download Keys)") } HorizontalDivider() Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp) ) { OutlinedTextField( modifier = Modifier.weight(1f), label = { Text(text = "Currency") }, value = viewModel.currency, onValueChange = {}, enabled = false ) OutlinedTextField( modifier = Modifier.weight(1f), label = { Text(text = "Amount") }, value = viewModel.amountStr, onValueChange = viewModel::handleInputAmt, isError = viewModel.amountStr.isEmpty(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) ) } OutlinedTextField( modifier = Modifier.fillMaxWidth(), label = { Text(text = "POS message ID") }, value = viewModel.posReference, onValueChange = { viewModel.posReference = it }, ) TextButton( onClick = { viewModel.resetRandomPosReference() }, modifier = Modifier.fillMaxWidth() ) { Icon(imageVector = Icons.Default.Refresh, contentDescription = null) Spacer(modifier = Modifier.size(4.dp)) Text(text = "Set random POS message ID") } Button(onClick = { launcher.launch( PoiRequest.ActionNew( tranType = TranType.SALE, amount = Amount( viewModel.amountStr.toBigDecimal(), Currency.getInstance(viewModel.currency), ), profileId = "prof_01HSJR9XQ353KN7YWXRXGNKD0K", preferredAcceptanceTag = "SME", forcePaymentMethod = listOf(PaymentMethod.VISA, PaymentMethod.MASTERCARD), description = "description 123", posReference = viewModel.posReference, forceFetchProfile = true, cvmSignatureMode = CvmSignatureMode.ELECTRONIC_SIGNATURE ) ) }) { Text(text = "PoiRequest.ActionNew") } HorizontalDivider() Text(text = "With UI\nActivity result launcher", style = MaterialTheme.typography.titleLarge) Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionVoid(it) launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionVoid") } Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionLinkedRefund(it) launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionLinkedRefund (full amt)") } Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionLinkedRefund(it, Amount(BigDecimal("0.5"), Currency.getInstance(viewModel.currency))) launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionLinkedRefund (partial amt)") } Button(onClick = { completedRefundTranId?.let { val action = PoiRequest.ActionVoid(it) launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionVoid (using refund tran id)") } Button(onClick = { completedSaleTranId?.let { val query = PoiRequest.Query(Referencable.TranId(it)) launcher.launch(query) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.Query (TranId)") } Button(onClick = { completedSalePosReference?.let { val query = PoiRequest.Query(Referencable.PosReference(it)) launcher.launch(query) } ?: viewModel.writeMessage("No pos ref") }) { Text(text = "PoiRequest.Query (PosReference)") } Button(onClick = { completedSaleRequestId?.let { val query = PoiRequest.Query(Referencable.RequestId(it)) launcher.launch(query) } ?: viewModel.writeMessage("No poi req id") }) { Text(text = "PoiRequest.Query (RequestId)") } HorizontalDivider() Text(text = "Without UI\nSuspended API", style = MaterialTheme.typography.titleLarge) Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionVoid(it) lifecycleScope.launch { HeadlessService.createAction(action).also { viewModel.writeMessage("createAction: $it") } } } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionVoid") } Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionLinkedRefund(it) lifecycleScope.launch { HeadlessService.createAction(action).also { viewModel.writeMessage("createAction: $it") } } launcher.launch(action) } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionLinkedRefund (full amt)") } Button(onClick = { completedSaleTranId?.let { val action = PoiRequest.ActionLinkedRefund(it, Amount(BigDecimal("0.5"), Currency.getInstance(viewModel.currency))) lifecycleScope.launch { HeadlessService.createAction(action).also { viewModel.writeMessage("createAction: $it") } } } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.ActionLinkedRefund (partial amt)") } Button(onClick = { completedSaleTranId?.let { val query = Referencable.TranId(it) lifecycleScope.launch { HeadlessService.getTransaction(query).also { viewModel.writeMessage("queryTransaction: $it") } } } ?: viewModel.writeMessage("No tran ID") }) { Text(text = "PoiRequest.Query (TranId)") } Button(onClick = { completedSalePosReference?.let { val query = Referencable.PosReference(it) lifecycleScope.launch { HeadlessService.getTransaction(query).also { viewModel.writeMessage("queryTransaction: $it") } } } ?: viewModel.writeMessage("No pos ref") }) { Text(text = "PoiRequest.Query (PosReference)") } Button(onClick = { completedSaleRequestId?.let { val query = Referencable.RequestId(it) lifecycleScope.launch { HeadlessService.getTransaction(query).also { viewModel.writeMessage("queryTransaction: $it") } } } ?: viewModel.writeMessage("No req id") }) { Text(text = "PoiRequest.Query (RequestId)") } } } } }
ms-example-sdk-headless/compose/src/main/java/com/theminesec/example/headless/ClientApp.kt
1986727748
package com.theminesec.example.headless import android.app.Application import android.util.Log import com.theminesec.example.headless.util.TAG import com.theminesec.sdk.headless.HeadlessSetup import com.theminesec.sdk.headless.model.WrappedResult import com.theminesec.sdk.headless.model.setup.SdkInitResp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ClientApp : Application() { private val appScope = CoroutineScope(Dispatchers.Main) var sdkInitResp: WrappedResult<SdkInitResp>? = null private set override fun onCreate() { super.onCreate() appScope.launch { val clientAppInitRes = HeadlessSetup.initSoftPos(this@ClientApp, "public-test.license") Log.d(TAG, "$clientAppInitRes") sdkInitResp = clientAppInitRes } } }
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/Constant.kt
3393612312
package com.theminesec.example.headless_xml const val TAG = "HL/ ClientAppXml"
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/ClientHeadlessImpl.kt
1173905042
package com.theminesec.example.headless_xml import android.annotation.SuppressLint import android.content.ContentResolver import android.content.Context import android.graphics.Color import android.graphics.SurfaceTexture import android.media.MediaPlayer import android.net.Uri import android.util.Log import android.view.LayoutInflater import android.view.Surface import android.view.TextureView import android.view.View import android.widget.ImageView import android.widget.LinearLayout import android.widget.LinearLayout.LayoutParams import android.widget.TextView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.constraintlayout.widget.ConstraintLayout import androidx.databinding.DataBindingUtil import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import com.theminesec.example.headless_xml.databinding.CompAmountDisplayBinding import com.theminesec.example.headless_xml.databinding.CompOrSignatureScreenBinding import com.theminesec.example.headless_xml.databinding.CompOrUiStateDisplayBinding import com.theminesec.sdk.headless.HeadlessActivity import com.theminesec.sdk.headless.model.transaction.Amount import com.theminesec.sdk.headless.model.transaction.PaymentMethod import com.theminesec.sdk.headless.model.transaction.WalletType import com.theminesec.sdk.headless.ui.* import com.theminesec.sdk.headless.ui.component.SignaturePad import com.theminesec.sdk.headless.ui.component.SignatureState import com.theminesec.sdk.headless.ui.component.resource.getImageRes import kotlinx.coroutines.launch class ClientHeadlessImpl : HeadlessActivity() { override fun provideTheme(): ThemeProvider { return ClientThemeProvider() } private val provider = ClientViewProvider() override fun provideUi(): UiProvider { return UiProvider( amountView = provider, progressIndicatorView = provider, awaitCardIndicatorView = provider, acceptanceMarksView = provider, signatureScreenView = provider, uiStateDisplayView = provider ) } } @SuppressLint("SetTextI18n") class ClientViewProvider : AmountView, ProgressIndicatorView, AwaitCardIndicatorView, AcceptanceMarksView, SignatureScreenView, UiStateDisplayView { private fun Int.intToDp(context: Context): Int = (this * context.resources.displayMetrics.density).toInt() override fun createAmountView(context: Context, amount: Amount, description: String?): View { val inflater = LayoutInflater.from(context) return DataBindingUtil.inflate<CompAmountDisplayBinding>(inflater, R.layout.comp_amount_display, null, false) .apply { root.layoutParams = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT ) this.amount = amount.value.toString() this.description = "dummy description" } .root // return LinearLayout(context).apply { // orientation = LinearLayout.VERTICAL // layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) // addView(TextView(context) // .apply { // textSize = 30F // textAlignment = TEXT_ALIGNMENT_CENTER // text = "Total amount here" // }) // addView(TextView(context) // .apply { // textSize = 40F // textAlignment = TEXT_ALIGNMENT_CENTER // text = "${amount.currency.currencyCode}${amount.value}" // }) // } } override fun createAwaitCardIndicatorView(context: Context): View { val mediaPlayer = MediaPlayer() return TextureView(context).apply { surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) { val videoUri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(context.packageName) .appendPath("${R.raw.demo_await}") .build() mediaPlayer.apply { setDataSource(context, videoUri) setSurface(Surface(surface)) isLooping = true prepareAsync() setOnPreparedListener { start() } } } override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = true override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} } } } override fun createAcceptanceMarksView(context: Context, supportedPayments: List<PaymentMethod>, showWallet: Boolean): View { return LinearLayout(context).apply { orientation = LinearLayout.HORIZONTAL val iconLp = LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, ).apply { marginEnd = 16.intToDp(context) } supportedPayments.forEach { pm -> addView(ImageView(context).apply { setImageResource(pm.getImageRes()).apply { layoutParams = iconLp } }) } if (showWallet) { addView(ImageView(context).apply { setImageResource(WalletType.APPLE_PAY.getImageRes()) }) } } } override fun createProgressIndicatorView(context: Context): View { val mediaPlayer = MediaPlayer() return TextureView(context).apply { surfaceTextureListener = object : TextureView.SurfaceTextureListener { override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) { val videoUri = Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(context.packageName) .appendPath("${R.raw.demo_processing}") .build() mediaPlayer.apply { setDataSource(context, videoUri) setSurface(Surface(surface)) isLooping = true prepareAsync() setOnPreparedListener { start() } } } override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {} override fun onSurfaceTextureDestroyed(surface: SurfaceTexture): Boolean = true override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {} } } // return CircularProgressIndicator(context).apply { // layoutParams = LayoutParams( // LayoutParams.MATCH_PARENT, // LayoutParams.MATCH_PARENT // ) // indicatorSize = 200.intToDp(context) // trackThickness = 8.intToDp(context) // isIndeterminate = true // trackColor = Color.TRANSPARENT // setIndicatorColor(Color.parseColor("#FFD503")) // isVisible = true // } } override fun createSignatureView( context: Context, amount: Amount?, maskedAccount: String?, paymentMethod: PaymentMethod?, approvalCode: String?, signatureState: SignatureState, onConfirm: () -> Unit ): View { val inflater = LayoutInflater.from(context) val binding = DataBindingUtil.inflate<CompOrSignatureScreenBinding>(inflater, R.layout.comp_or_signature_screen, null, false) .apply { root.layoutParams = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.MATCH_PARENT ) this.amount = amount this.maskedAccount = maskedAccount this.paymentMethod = paymentMethod this.approvalCode = approvalCode } binding.composeViewSignaturePad.apply { setViewCompositionStrategy(ViewCompositionStrategy.Default) setContent { SignaturePad(state = signatureState) } } binding.btnClear.apply { (context as LifecycleOwner).lifecycleScope.launch { signatureState.signatureLines.collect { isEnabled = it.isNotEmpty() } } setOnClickListener { signatureState.clearSignatureLines() } } binding.btnConfirm.apply { (context as LifecycleOwner).lifecycleScope.launch { signatureState.signatureLines.collect { isEnabled = it.isNotEmpty() } } setOnClickListener { onConfirm() } } return binding.root } private var tv: TextView? = null override fun createUiStateDisplayView( context: Context, uiState: UiState, ): View { val inflater = LayoutInflater.from(context) val binding = DataBindingUtil.inflate<CompOrUiStateDisplayBinding>(inflater, R.layout.comp_or_ui_state_display, null, false) .apply { root.layoutParams = ConstraintLayout.LayoutParams( ConstraintLayout.LayoutParams.MATCH_PARENT, ConstraintLayout.LayoutParams.WRAP_CONTENT ) } tv = binding.tvCountdown binding.tvTitle.text = context.getString(uiState.getTitleRes()) binding.tvDesc.text = context.getString(uiState.getDescriptionRes()) when (uiState) { is UiState.Awaiting -> { binding.tvCountdown.visibility = View.VISIBLE binding.containerPms.visibility = View.VISIBLE binding.containerPms.addView(createAcceptanceMarksView(context, uiState.supportedPayments, showWallet = true)) } is UiState.Processing -> { binding.tvCountdown.visibility = View.VISIBLE } else -> { binding.tvCountdown.visibility = View.GONE } } return binding.root } override fun onCountdownUpdate(countdownSec: Int) { Log.d(TAG, "xml onCountdownUpdate: $countdownSec") tv?.text = "${countdownSec}s" } } class ClientThemeProvider : ThemeProvider() { override fun provideColors(darkTheme: Boolean): HeadlessColors { return HeadlessColorsLight().copy( primary = Color.parseColor("#FFD503"), foreground = Color.parseColor("#333333"), mutedForeground = Color.parseColor("#4E3C2E") ) } }
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/ContentViewBindingDelegate.kt
66750436
package com.theminesec.example.headless_xml import androidx.annotation.LayoutRes import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import kotlin.reflect.KProperty class ContentViewBindingDelegate<in R : AppCompatActivity, out T : ViewDataBinding>( @LayoutRes private val layoutRes: Int, ) { private var binding: T? = null operator fun getValue(activity: R, property: KProperty<*>): T { if (binding == null) { binding = DataBindingUtil.setContentView<T>(activity, layoutRes).apply { lifecycleOwner = activity } } return binding!! } } fun <R : AppCompatActivity, T : ViewDataBinding> contentView( @LayoutRes layoutRes: Int, ): ContentViewBindingDelegate<R, T> = ContentViewBindingDelegate(layoutRes)
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/ClientMain.kt
29090844
package com.theminesec.example.headless_xml import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import com.theminesec.example.headless_xml.databinding.ActivityMainBinding import com.theminesec.sdk.headless.HeadlessActivity import com.theminesec.sdk.headless.HeadlessSetup import com.theminesec.sdk.headless.model.transaction.* import kotlinx.coroutines.launch import ulid.ULID import java.util.* class ClientMain : AppCompatActivity() { private val binding: ActivityMainBinding by contentView(R.layout.activity_main) private val launcher = registerForActivityResult( HeadlessActivity.contract(ClientHeadlessImpl::class.java) ) { Log.d(TAG, "onCreate: WrappedResult<Transaction>: $it}") } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.view = this } fun checkInitStatus() { val sdkInitResp = (application as ClientApp).sdkInitResp Log.d(TAG, "checkInitStatus: $sdkInitResp") } fun initialSetup() = lifecycleScope.launch { val res = HeadlessSetup.initialSetup(this@ClientMain) Log.d(TAG, "setupInitial: $res") } fun launchNewSale() { launcher.launch( PoiRequest.ActionNew( tranType = TranType.SALE, amount = Amount( "10.00".toBigDecimal(), Currency.getInstance("HKD"), ), profileId = "prof_01HSJR9XQ353KN7YWXRXGNKD0K", preferredAcceptanceTag = "SME", forcePaymentMethod = null, description = "description 123", posReference = "pos_${ULID.randomULID()}", forceFetchProfile = true, cvmSignatureMode = CvmSignatureMode.ELECTRONIC_SIGNATURE ) ) } fun launchNewSaleWithSign() { launcher.launch( PoiRequest.ActionNew( tranType = TranType.SALE, amount = Amount( "1001.00".toBigDecimal(), Currency.getInstance("HKD"), ), profileId = "prof_01HSJR9XQ353KN7YWXRXGNKD0K", preferredAcceptanceTag = "SME", forcePaymentMethod = listOf(PaymentMethod.VISA, PaymentMethod.MASTERCARD), description = "description 123", posReference = "pos_${ULID.randomULID()}", forceFetchProfile = true, cvmSignatureMode = CvmSignatureMode.ELECTRONIC_SIGNATURE ) ) } fun launchNewSaleWrongProfile() { launcher.launch( PoiRequest.ActionNew( tranType = TranType.SALE, amount = Amount( "20.00".toBigDecimal(), Currency.getInstance("HKD"), ), profileId = "wrong profile", forceFetchProfile = false ) ) } }
ms-example-sdk-headless/xml/src/main/java/com/theminesec/example/headless_xml/ClientApp.kt
1378584054
package com.theminesec.example.headless_xml import android.app.Application import android.util.Log import com.theminesec.sdk.headless.HeadlessSetup import com.theminesec.sdk.headless.model.WrappedResult import com.theminesec.sdk.headless.model.setup.SdkInitResp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class ClientApp : Application() { private val appScope = CoroutineScope(Dispatchers.Main) var sdkInitResp: WrappedResult<SdkInitResp>? = null private set override fun onCreate() { super.onCreate() appScope.launch { val clientAppInitRes = HeadlessSetup.initSoftPos(this@ClientApp, "test.license") Log.d(TAG, "$clientAppInitRes") sdkInitResp = clientAppInitRes } } }
Weather4/app/src/androidTest/java/com/example/weather2/ExampleInstrumentedTest.kt
3195131069
package com.example.weather2 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("com.example.weather2", appContext.packageName) } }
Weather4/app/src/test/java/com/example/weather2/ExampleUnitTest.kt
23970123
package com.example.weather2 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) } }
Weather4/app/src/main/java/com/example/weather2/App.kt
955421199
package com.example.weather2 import android.app.Application import androidx.room.Room import com.example.weather2.data.room.AppDatabase class App : Application() { companion object { lateinit var weatherDatabase: AppDatabase } override fun onCreate() { super.onCreate() weatherDatabase = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "weather-db").allowMainThreadQueries() .build() } }
Weather4/app/src/main/java/com/example/weather2/response/Hour.kt
3330487897
package com.example.weather2.response data class Hour( val time_epoch: Long, val time: String, val temp_c: Double, val temp_f: Double, val is_day: Int, val condition: Condition, val wind_mph: Double, val wind_kph: Double, val wind_degree: Int, val wind_dir: String, val pressure_mb: Double, val pressure_in: Double, val precip_mm: Double, val precip_in: Double, val humidity: Int, val cloud: Int, val feelslike_c: Double, val feelslike_f: Double, val vis_km: Double, val vis_miles: Double, val uv: Double, val gust_mph: Double, val dayOfWeek: String, val gust_kph: Double )
Weather4/app/src/main/java/com/example/weather2/response/Astro.kt
1481119331
package com.example.weather2.response data class Astro( val sunrise: String, val sunset: String, val moonrise: String, val moonset: String, val moon_phase: String, val moon_illumination: String, val is_moon_up: Int, val is_sun_up: Int )
Weather4/app/src/main/java/com/example/weather2/response/Location.kt
742086816
package com.example.weather2.response data class Location( val name: String, val region: String, val country: String, val lat: Double, val lon: Double, val tz_id: String, val localtime_epoch: Long, val localtime: String )
Weather4/app/src/main/java/com/example/weather2/response/Day.kt
854186526
package com.example.weather2.response data class Day( val maxtemp_c: Double, val maxtemp_f: Double, val mintemp_c: Double, val mintemp_f: Double, val avgtemp_c: Double, val avgtemp_f: Double, val maxwind_mph: Double, val maxwind_kph: Double, val totalprecip_mm: Double, val totalprecip_in: Double, val totalsnow_cm: Double, val avgvis_km: Double, val avgvis_miles: Double, val avghumidity: Int, val daily_will_it_rain: Int, val daily_chance_of_rain: String, val daily_will_it_snow: Int, val daily_chance_of_snow: String, val condition: Condition, val uv: Double )
Weather4/app/src/main/java/com/example/weather2/response/Condition.kt
3793233750
package com.example.weather2.response data class Condition( val text: String, val icon: String, val code: Int )
Weather4/app/src/main/java/com/example/weather2/response/ForecastDay.kt
3145390629
package com.example.weather2.response data class ForecastDay( val date: String, val date_epoch: Long, val day: Day, val astro: Astro, val hour: List<Hour> )
Weather4/app/src/main/java/com/example/weather2/response/WeatherResponse.kt
1309403484
package com.example.weather2.response data class WeatherResponse( val location: Location, val current: Current, val forecast: Forecast )
Weather4/app/src/main/java/com/example/weather2/response/Forecast.kt
1465842367
package com.example.weather2.response data class Forecast( val forecastday: List<ForecastDay> )
Weather4/app/src/main/java/com/example/weather2/response/Current.kt
482132337
package com.example.weather2.response data class Current( val last_updated_epoch: Long, val last_updated: String, val temp_c: Double, val temp_f: Double, val is_day: Int, val condition: Condition, val wind_mph: Double, val wind_kph: Double, val wind_degree: Int, val wind_dir: String, val pressure_mb: Double, val pressure_in: Double, val precip_mm: Double, val precip_in: Double, val humidity: Int, val cloud: Int, val feelslike_c: Double, val feelslike_f: Double, val vis_km: Double, val vis_miles: Double, val uv: Double, val gust_mph: Double, val gust_kph: Double )
Weather4/app/src/main/java/com/example/weather2/data/WeatherRepository.kt
2652809028
package com.example.weather2.data import com.example.weather2.data.room.WeatherEntity import com.example.weather2.data.room.WeatherDao import com.example.weather2.response.WeatherResponse class WeatherRepository( private val api: WeatherApi, private val weatherDao: WeatherDao ) { suspend fun getWeather(location: String, days: Int, aqi: String, alerts: String): WeatherResponse { val key = "8a8b25949fec425599f92306240304" val response = api.getForecast(key, location, days, aqi, alerts) val weatherEntity = convertResponseToEntity(response) weatherDao.insert(weatherEntity) return response } suspend fun getLocalWeather(): List<WeatherEntity> { return weatherDao.getAll() } private fun convertResponseToEntity(response: WeatherResponse): WeatherEntity { val temperature = response.current.temp_c return WeatherEntity( id = 0, temperature = temperature ) } }
Weather4/app/src/main/java/com/example/weather2/data/room/WeatherEntity.kt
3011071809
package com.example.weather2.data.room import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class WeatherEntity( @PrimaryKey(autoGenerate = true) val id: Int, val temperature: Double, )
Weather4/app/src/main/java/com/example/weather2/data/room/AppDatabase.kt
703339594
package com.example.weather2.data.room import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [WeatherEntity::class], version = 1) abstract class AppDatabase : RoomDatabase() { abstract fun weatherDao(): WeatherDao }
Weather4/app/src/main/java/com/example/weather2/data/room/WeatherDao.kt
3861892863
package com.example.weather2.data.room import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface WeatherDao { @Query("SELECT * FROM weatherentity") fun getAll(): List<WeatherEntity> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(weather: WeatherEntity) @Query("DELETE FROM weatherentity") suspend fun deleteAll() }
Weather4/app/src/main/java/com/example/weather2/data/WeatherModule.kt
3238078207
package com.example.weather2.data import com.example.weather2.BuildConfig import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitInstance { private val client = OkHttpClient.Builder().apply { addInterceptor(HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }) }.build() private val retrofit by lazy { Retrofit.Builder() .baseUrl(BuildConfig.API) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() } val api: WeatherApi by lazy { retrofit.create(WeatherApi::class.java) } }
Weather4/app/src/main/java/com/example/weather2/data/WeatherApi.kt
1520705245
package com.example.weather2.data import com.example.weather2.response.WeatherResponse import retrofit2.http.GET import retrofit2.http.Query interface WeatherApi { @GET("forecast.json") suspend fun getForecast( @Query("key") key: String, @Query("q") location: String, @Query("days") days: Int, @Query("aqi") aqi: String, @Query("alerts") alerts: String ): WeatherResponse }
Weather4/app/src/main/java/com/example/weather2/domain/GetWeatherUseCase.kt
2994619399
package com.example.weather2.domain import com.example.weather2.data.WeatherRepository import com.example.weather2.response.WeatherResponse class GetWeatherUseCase(private val repository: WeatherRepository) { suspend fun execute(location: String, days: Int, aqi: String, alerts: String): WeatherResponse { return repository.getWeather(location, days, aqi, alerts) } }
Weather4/app/src/main/java/com/example/weather2/presentation/MainActivity.kt
1408065212
package com.example.weather2.presentation import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import androidx.room.Room import com.example.weather2.data.RetrofitInstance import com.example.weather2.data.WeatherRepository import com.example.weather2.data.room.AppDatabase import com.example.weather2.data.room.WeatherDao import com.example.weather2.databinding.ActivityMainBinding import com.example.weather2.domain.GetWeatherUseCase import com.squareup.picasso.Picasso class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private lateinit var viewModel: WeatherViewModel private val adapter = WeatherAdapter() private lateinit var weatherDao: WeatherDao private val locations = listOf("London", "New York", "Paris", "Moscow", "Bishkek") private var currentLocationIndex = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) supportActionBar?.hide() setContentView(binding.root) val db = Room.databaseBuilder( applicationContext, AppDatabase::class.java, "weather-database" ).build() weatherDao = db.weatherDao() val api = RetrofitInstance.api val repository = WeatherRepository(api, weatherDao) val getWeatherUseCase = GetWeatherUseCase(repository) viewModel = ViewModelProvider(this, WeatherViewModelFactory(getWeatherUseCase))[WeatherViewModel::class.java] binding.recyclerView.adapter = adapter val days = 7 val aqi = "no" val alerts = "no" getWeatherForLocation(locations[currentLocationIndex], days, aqi, alerts) binding.arrow.setOnClickListener { currentLocationIndex = (currentLocationIndex + 1) % locations.size getWeatherForLocation(locations[currentLocationIndex], days, aqi, alerts) } } private fun getWeatherForLocation(location: String, days: Int, aqi: String, alerts: String) { viewModel.getWeather(location, days, aqi, alerts) viewModel.weatherResponse.observe(this) { response -> val hoursWithDays = response.forecast.forecastday.flatMap { day -> day.hour.map { hour -> Pair(hour, day) } } val sortedHoursWithDays = hoursWithDays.sortedBy { it.first.time_epoch } adapter.submitList(sortedHoursWithDays) val currentWeather = response.current binding.tvToday.text = "Today" binding.tvGradus.text = "${currentWeather.temp_c}°C" binding.tvWeather.text = currentWeather.condition.text binding.tvCity.text = response.location.name val iconUrl = "https:${currentWeather.condition.icon}" Picasso.get() .load(iconUrl) .into(binding.ivIcon) } } }
Weather4/app/src/main/java/com/example/weather2/presentation/WeatherViewModel.kt
1818535401
package com.example.weather2.presentation import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.weather2.domain.GetWeatherUseCase import com.example.weather2.response.WeatherResponse import kotlinx.coroutines.launch class WeatherViewModel(private val getWeatherUseCase: GetWeatherUseCase) : ViewModel() { val weatherResponse: MutableLiveData<WeatherResponse> = MutableLiveData() fun getWeather(location: String, days: Int, aqi: String, alerts: String) { viewModelScope.launch { val response = getWeatherUseCase.execute(location, days, aqi, alerts) weatherResponse.postValue(response) } } }
Weather4/app/src/main/java/com/example/weather2/presentation/WeatherViewModelFactory.kt
146194160
package com.example.weather2.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.weather2.domain.GetWeatherUseCase class WeatherViewModelFactory(private val getWeatherUseCase: GetWeatherUseCase) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(WeatherViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return WeatherViewModel(getWeatherUseCase) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
Weather4/app/src/main/java/com/example/weather2/presentation/WeatherAdapter.kt
1765411561
package com.example.weather2.presentation import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.example.weather2.databinding.ItemWeatherBinding import com.example.weather2.response.Hour import com.example.weather2.response.ForecastDay import java.text.SimpleDateFormat import java.util.* class WeatherAdapter : ListAdapter<Pair<Hour, ForecastDay>, WeatherAdapter.WeatherViewHolder>( DiffCallback() ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeatherViewHolder { val binding = ItemWeatherBinding.inflate(LayoutInflater.from(parent.context), parent, false) return WeatherViewHolder(binding) } override fun onBindViewHolder(holder: WeatherViewHolder, position: Int) { val currentItem = getItem(position) holder.bind(currentItem.first, currentItem.second) } inner class WeatherViewHolder(private val binding: ItemWeatherBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(hour: Hour, forecastDay: ForecastDay) { binding.apply { if (hour.time.endsWith("00:00")) { tvDay.text = getDayOfWeek(forecastDay.date) } else { tvDay.text = "" } tvTime.text = getTime(hour.time) tvGradusRv.text = "${hour.temp_c}C" tvWeatherRv.text = hour.condition.text } } private fun getDayOfWeek(date: String): String { val format = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val date = format.parse(date) val formatDayOfWeek = SimpleDateFormat("EEEE", Locale.getDefault()) return formatDayOfWeek.format(date) } private fun getTime(time: String): String { val format = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) val date = format.parse(time) val formatTime = SimpleDateFormat("HH:mm", Locale.getDefault()) return formatTime.format(date) } } class DiffCallback : DiffUtil.ItemCallback<Pair<Hour, ForecastDay>>() { override fun areItemsTheSame(oldItem: Pair<Hour, ForecastDay>, newItem: Pair<Hour, ForecastDay>) = oldItem.first.time_epoch == newItem.first.time_epoch override fun areContentsTheSame(oldItem: Pair<Hour, ForecastDay>, newItem: Pair<Hour, ForecastDay>) = oldItem == newItem } }
Android-advance-11_2-Food-app/app/src/androidTest/java/com/example/assignment11_2/ExampleInstrumentedTest.kt
1806943946
package com.example.assignment11_2 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("com.example.assignment11_2", appContext.packageName) } }
Android-advance-11_2-Food-app/app/src/test/java/com/example/assignment11_2/ExampleUnitTest.kt
2044569577
package com.example.assignment11_2 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) } }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/viewmodel/FoodViewModel.kt
2195392715
package com.example.assignment11_2.viewmodel import android.app.Application import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import com.example.assignment11_2.model.Food import com.example.assignment11_2.repository.FoodRepository import kotlinx.coroutines.launch import java.lang.IllegalArgumentException class FoodViewModel (app : Application):ViewModel(){ private val foodRepository : FoodRepository = FoodRepository(app) class FoodViewModelFactory(private val application: Application) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(FoodViewModel::class.java)) { return FoodViewModel(application) as T } throw IllegalArgumentException("Unable construct viewModel") } } fun insertFood(food: Food) = viewModelScope.launch { foodRepository.insertFood(food) } fun updateFood(food: Food)=viewModelScope.launch { foodRepository.updateFood(food) } fun deleteFood(id:Int)=viewModelScope.launch { foodRepository.deleteFood(id) } fun getAllFoods():LiveData<List<Food>> = foodRepository.getAllFood() }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/database/FoodDatabase.kt
2252223949
package com.example.assignment11_2.database import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import com.example.assignment11_2.database.dao.FoodDao import com.example.assignment11_2.model.Food @Database(entities = [Food::class], version = 1) abstract class FoodDatabase : RoomDatabase() { abstract fun getFoodDao(): FoodDao companion object { @Volatile private var instance: FoodDatabase? = null fun getInstance(context: Context): FoodDatabase { if (instance == null) { instance = Room.databaseBuilder(context, FoodDatabase::class.java, "FoodDatabase").build() } return instance!! } } }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/database/dao/FoodDao.kt
1069914359
package com.example.assignment11_2.database.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.Update import com.example.assignment11_2.model.Food @Dao interface FoodDao { @Insert suspend fun insertFood(food: Food) @Update suspend fun updateFood(food: Food) @Query("DELETE FROM food_table WHERE id = :id") suspend fun deleteFood(id: Int) @Query("SELECT * FROM food_table") fun getAllFoods():LiveData<List<Food>> @Query("SELECT * FROM food_table WHERE name_col=:name") fun getFoodByName(name:String):LiveData<List<Food>> }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/repository/FoodRepository.kt
3132148080
package com.example.assignment11_2.repository import android.app.Application import androidx.lifecycle.LiveData import com.example.assignment11_2.database.FoodDatabase import com.example.assignment11_2.database.dao.FoodDao import com.example.assignment11_2.model.Food class FoodRepository(app : Application) { private val foodDao : FoodDao init{ val foodDatabase: FoodDatabase = FoodDatabase.getInstance(app) foodDao = foodDatabase.getFoodDao() } suspend fun insertFood(food: Food) = foodDao.insertFood(food) suspend fun updateFood(food: Food) = foodDao.updateFood(food) suspend fun deleteFood(id : Int) = foodDao.deleteFood(id) fun getAllFood():LiveData<List<Food>> = foodDao.getAllFoods() }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/fragments/FoodDetailFragment.kt
2352664763
package com.example.assignment11_2.fragments import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.example.assignment10.R class FoodDetailFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_food_detail, container, false) } companion object { @JvmStatic fun newInstance(param1: String, param2: String) = FoodDetailFragment().apply { arguments = Bundle().apply { // putString(ARG_PARAM1, param1) // putString(ARG_PARAM2, param2) } } } }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/adapter/FoodAdapter.kt
1475620892
package com.example.assignment11_2.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.assignment10.R import com.example.assignment10.databinding.FoodItemBinding import com.example.assignment11_2.model.Food import java.text.NumberFormat import java.util.Locale class FoodAdapter : RecyclerView.Adapter<FoodAdapter.ViewHolder>() { val foodList = listOf( Food( id = 1, name = "Hamburger testcase long text", description = "Delicious hamburger with beef patty, lettuce, tomato, and cheese", price = 5545499.3, image = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRrt1EInzip1NZ71yE0yKJ99ZtDqzzO-7iqtw&s" ), Food( id = 2, name = "Pizza", description = "Tasty pizza topped with pepperoni, mushrooms, and mozzarella cheese", price = 8343443.99, image = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTFESPeeQZO1U-pTrKDWKPjrF5zYvEFARa2Vg&s" ), Food( id = 3, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 1235.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 4, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 12040.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 5, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 124554.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 6, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 1245124.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 7, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 123125.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 8, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 12235.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), Food( id = 9, name = "Sushi", description = "Fresh sushi rolls with salmon, avocado, and cucumber", price = 12235325.99, image = "https://down-vn.img.susercontent.com/file/vn-11134207-7r98o-lounwyboavrk9d" ), ) inner class ViewHolder(item: View) : RecyclerView.ViewHolder(item) { private val binding: FoodItemBinding = FoodItemBinding.bind(item) val foodName = binding.tvFoodName val foodPrice = binding.tvFoodPrice val foodDescription = binding.tvFoodDescription val foodImage = binding.imgFood } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodAdapter.ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.food_item,parent,false) return ViewHolder(view) } override fun onBindViewHolder(holder: FoodAdapter.ViewHolder, position: Int) { holder.foodName.text = foodList[position].name holder.foodPrice.text = NumberFormat.getCurrencyInstance(Locale("vi", "VN")).format(foodList[position].price) holder.foodDescription.text = foodList[position].description Glide.with(holder.itemView.context).load(foodList[position].image) .error(R.drawable.img_no_available).into(holder.foodImage) } override fun getItemCount(): Int { return foodList.size } }
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/model/Food.kt
675023753
package com.example.assignment11_2.model import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize @Parcelize @Entity(tableName = "food_table") class Food( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Int? = 0, @ColumnInfo(name = "name_col") var name: String = "", @ColumnInfo(name = "description_col") var description: String = "", @ColumnInfo(name = "price_col") var price: Double, @ColumnInfo(name="image-col") val image: String ) : Parcelable
Android-advance-11_2-Food-app/app/src/main/java/com/example/assignment11_2/activities/MainActivity.kt
1055992333
package com.example.assignment11_2.activities import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import com.example.assignment10.R import com.example.assignment10.databinding.ActivityMainBinding import com.example.assignment11_2.adapter.FoodAdapter import com.example.assignment11_2.model.Food import com.example.assignment11_2.viewmodel.FoodViewModel class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val foodViewModel: FoodViewModel by lazy { ViewModelProvider( this, FoodViewModel.FoodViewModelFactory(this.application) )[FoodViewModel::class.java] } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } // RecyclerView val adapter = FoodAdapter() binding.rvFoods.layoutManager = GridLayoutManager(this,2) binding.rvFoods.adapter = adapter } }
firstKotlin/app/src/androidTest/java/com/example/firstkotlin/ExampleInstrumentedTest.kt
2199436650
package com.example.firstkotlin 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("com.example.firstkotlin", appContext.packageName) } }
firstKotlin/app/src/test/java/com/example/firstkotlin/ExampleUnitTest.kt
612195727
package com.example.firstkotlin 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) } }
firstKotlin/app/src/main/java/com/example/firstkotlin/RView/FifthActivity.kt
4057098233
package com.example.firstkotlin.RView import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.firstkotlin.R class FifthActivity:AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fifth_layout) } }
firstKotlin/app/src/main/java/com/example/firstkotlin/RView/FifthAdapter.kt
3198191345
package com.example.firstkotlin.RView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ViewHolder import androidx.recyclerview.widget.RecyclerView.inflate import com.example.firstkotlin.ListView.Fruit import com.example.firstkotlin.R //class FifthAdapter:RecyclerView.Adapter<ViewHolder>() { // // inner class ViewHolder(view: View):RecyclerView.ViewHolder(view){ // private val imageView:ImageView = view.findViewById(R.id.fruitImage) // private val textView:TextView = view.findViewById(R.id.fruitName) // // fun bindViewHolderItem(fruit: Fruit){ // imageView.setImageResource(fruit.imageId) // textView.text = fruit.name // } // } // // override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // val view = LayoutInflater.from(parent.context).inflate(R.layout.fruit_item,parent,false) // } // // override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { // TODO("Not yet implemented") // } // // override fun getItemCount(): Int { // TODO("Not yet implemented") // } // //}
firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/MainViewModel.kt
3534791902
package com.example.firstkotlin.ViewModel import androidx.lifecycle.ViewModel class MainViewModel : ViewModel() { var counter = 0 }
firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/VMLivingData/ClickCounterLD.kt
863606984
package com.example.firstkotlin.ViewModel.VMLivingData import android.content.SharedPreferences import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.content.edit import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import com.example.firstkotlin.R class ClickCounterLD:AppCompatActivity() { lateinit var viewModel: ClickCounterVMLD //延迟初始化,从轻量数据库取数据的 lateinit var sp: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.clickcounter_ld) //创建sp的示例,不过传递的常数并不知道是什么 sp = getSharedPreferences("data", MODE_PRIVATE) //为counterReserved设置初始的值 val counterReserved = sp.getInt("counter_reserved", 3) //创建VM实例 viewModel = ViewModelProvider(this, ClickCounterF(counterReserved)).get( ClickCounterVMLD::class.java) val plusOne = findViewById<Button>(R.id.plusOneBtn) plusOne.setOnClickListener { viewModel.plusOne() } val clear = findViewById<Button>(R.id.clearBtn) clear.setOnClickListener { viewModel.clear() } viewModel.counter.observe(this) { count -> val infoText = findViewById<TextView>(R.id.infoText) infoText.text = count.toString() } } override fun onPause() { super.onPause() sp.edit() { putInt("counter_reserved", viewModel.counter.value ?: 0) } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/VMLivingData/User.kt
2634410864
package com.example.firstkotlin.ViewModel.VMLivingData data class User(var firstName: String, var lastName: String, var age: Int)
firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/VMLivingData/ClickCounterF.kt
3841673842
package com.example.firstkotlin.ViewModel.VMLivingData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.firstkotlin.ViewModel.ClickCounterVM //这段代码很多不会的,交给以后的我吧 class ClickCounterF(private val countReserved: Int) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return ClickCounterVM(countReserved) as T } }
firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/VMLivingData/ClickCounterVMLD.kt
1630731007
package com.example.firstkotlin.ViewModel.VMLivingData import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class ClickCounterVMLD(countReserved: Int) : ViewModel() { private val userLiveData = MutableLiveData<User>() // val userName: LiveData<String> = Transformations.map(userLiveData) { user -> "${user.frist}" //这里我暂时不能理解,交给后来的人吧 val counter: LiveData<Int> get() = _counter private val _counter = MutableLiveData<Int>() //这里在init结构体中给counter设置数据,这样之前保存的计数值就可以在初始化的时候得到恢复 init { _counter.value = countReserved } fun plusOne() { val count = _counter.value ?: 0 _counter.value = count + 1 } fun clear() { _counter.value = 0 } }
firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/ClickCounter.kt
3383334180
package com.example.firstkotlin.ViewModel import android.content.SharedPreferences import android.os.Bundle import android.widget.Button import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.content.edit import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.get import com.example.firstkotlin.R class ClickCounter : AppCompatActivity() { lateinit var viewModel: ClickCounterVM //延迟初始化,从轻量数据库取数据的 lateinit var sp: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.clickcounter) //创建sp的示例,不过传递的常数并不知道是什么 sp = getSharedPreferences("data", MODE_PRIVATE) //为counterReserved设置初始的值 val counterReserved = sp.getInt("counter_reserved", 3) //创建VM实例 viewModel = ViewModelProvider(this,ClickCounterViewModelFactory(counterReserved)).get(ClickCounterVM::class.java) //设置按钮监听 val onPlusOne = findViewById<Button>(R.id.plusOneBtn) onPlusOne.setOnClickListener { viewModel.counter++ refreshCounter() } val clearBtn = findViewById<Button>(R.id.clearBtn) clearBtn.setOnClickListener { viewModel.counter = 0 refreshCounter() } refreshCounter() } private fun refreshCounter() { val infotext = findViewById<TextView>(R.id.infoText) infotext. text = viewModel.counter.toString() } /* * override fun onPause() {:这是 onPause() 方法的重写,它是 Android 生命周期的一部分。当应用程序失去焦点或进入后台时,系统会调用 onPause() 方法。 * super.onPause():这是调用父类的 onPause() 方法,以确保执行父类中的相关逻辑。通常,在重写生命周期方法时,我们会调用父类的方法。 * sp.edit {:这里的 sp 是一个 SharedPreferences 对象的实例,用于获取和修改 SharedPreferences 数据。通过调用 edit() 方法,我们获得了一个 SharedPreferences.Editor 对象,用于进行修改操作。 * putInt("count_reserved", viewModel.counter):这行代码使用 putInt() 方法将名为 "count_reserved" 的键和 viewModel.counter 的值存储到 SharedPreferences 中。viewModel.counter 是一个 ViewModel 中的计数器属性,它的值将被保存。 * */ override fun onPause() { super.onPause() sp.edit() { putInt("counter_reserved", viewModel.counter) } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/ClickCounterVM.kt
4266570684
package com.example.firstkotlin.ViewModel import androidx.lifecycle.ViewModel class ClickCounterVM(countReserved: Int) : ViewModel() { var counter = countReserved }
firstKotlin/app/src/main/java/com/example/firstkotlin/ViewModel/MainViewModelFactory.kt
378981095
package com.example.firstkotlin.ViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider //这段代码很多不会的,交给以后的我吧 class ClickCounterViewModelFactory(private val countReserved: Int) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return ClickCounterVM(countReserved) as T } }
firstKotlin/app/src/main/java/com/example/firstkotlin/ThirdActivity.kt
4236785566
package com.example.firstkotlin import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity class ThirdActivity:AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.third_layout) val extraData = intent.getStringExtra("extra_data") Log.d("页面3","页面2传过来的值是 $extraData") } }
firstKotlin/app/src/main/java/com/example/firstkotlin/MainActivity.kt
2823656001
package com.example.firstkotlin import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProvider import com.example.firstkotlin.Data.SharedPreferencesTest import com.example.firstkotlin.Data.WritingData import com.example.firstkotlin.BroadcastReceiver.BroadcastTest import com.example.firstkotlin.Data.SqlDataBase.SQLData_MainActivity import com.example.firstkotlin.Login.LoginActivity import com.example.firstkotlin.RView.FifthActivity import com.example.firstkotlin.ViewModel.ClickCounter import com.example.firstkotlin.ViewModel.MainViewModel import com.example.firstkotlin.ViewModel.VMLivingData.ClickCounterLD class MainActivity : AppCompatActivity() { lateinit var viewModel : MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_main) //按钮1的跳转设置 val button1 : Button = findViewById(R.id.button1) button1.setOnClickListener { val intent = Intent("com.example.activitytest.ACTION_START") startActivityForResult(intent,1) Toast.makeText(this,"点击了button1按钮",Toast.LENGTH_SHORT).show() } //按钮2的跳转设置 val button2 : Button = findViewById(R.id.button2) button2.setOnClickListener { val intent2 = Intent("android.intent.action.FORTH") startActivity(intent2) Toast.makeText(this,"点击了button1_2按钮",Toast.LENGTH_SHORT).show() } //按钮3的跳转设置 val button3 : Button = findViewById(R.id.button3) button3.setOnClickListener { val intent3 = Intent(this,FifthActivity::class.java) startActivity(intent3) Toast.makeText(this,"点击了button1_3按钮",Toast.LENGTH_SHORT).show() } //按钮4的跳转设置 val button4 : Button = findViewById(R.id.button4) button4.setOnClickListener { val intent4 = Intent(this,ClickCounter::class.java) startActivity(intent4) Toast.makeText(this,"点击了button1_4 VM按钮",Toast.LENGTH_SHORT).show() } //按钮5的跳转设置 val button5 : Button = findViewById(R.id.button5) button5.setOnClickListener { val intent5 = Intent(this,ClickCounterLD::class.java) startActivity(intent5) Toast.makeText(this,"点击了button1_5 VMLD按钮",Toast.LENGTH_SHORT).show() } //按钮5.5的跳转设置 val button5_5 : Button = findViewById(R.id.button5_5) button5_5.setOnClickListener { val intent5_5 = Intent(this, BroadcastTest::class.java) startActivity(intent5_5) Toast.makeText(this,"点击了button7 Share Preferences",Toast.LENGTH_SHORT).show() } //按钮5.7的跳转设置 val button5_7 : Button = findViewById(R.id.button5_7) button5_7.setOnClickListener { val intent5_7 = Intent(this, LoginActivity::class.java) startActivity(intent5_7) Toast.makeText(this,"点击了button 登录页",Toast.LENGTH_SHORT).show() } //按钮6的跳转设置 val button6 : Button = findViewById(R.id.button6) button6.setOnClickListener { val intent6 = Intent(this,WritingData::class.java) startActivity(intent6) Toast.makeText(this,"点击了button6 Data",Toast.LENGTH_SHORT).show() } //按钮7的跳转设置 val button7 : Button = findViewById(R.id.button7) button7.setOnClickListener { val intent7 = Intent(this,SharedPreferencesTest::class.java) startActivity(intent7) Toast.makeText(this,"点击了button7 Share Preferences",Toast.LENGTH_SHORT).show() } //按钮8的跳转设置 val button8 : Button = findViewById(R.id.button8) button8.setOnClickListener { val intent8 = Intent(this,SQLData_MainActivity::class.java) startActivity(intent8) Toast.makeText(this,"SQLdb",Toast.LENGTH_SHORT).show() } //viewModel的设置 //不可以直接去创建ViewModel的实例,而是一定要通过ViewModelProvider来获取ViewModel的实例 //ViewModelProvider(<你的Activity或Fragment实例>).get(<你的ViewModel>::class.java) viewModel = ViewModelProvider(this).get(MainViewModel::class.java) //声明按钮,设置按钮的响应 val plusonebtn = findViewById<Button>(R.id.plusOneBtn) plusonebtn.setOnClickListener { viewModel.counter++ //按按钮后执行动作,并把新值写入 refreshCounter() } //写入完了之后就会按顺序再到这里执行,这次展示的值就是新值 refreshCounter() } //给TextView赋值,一个方法 private fun refreshCounter() { val infoText = findViewById<TextView>(R.id.infoText) infoText.text = viewModel.counter.toString() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when(requestCode){ 1 -> if(resultCode == RESULT_OK){ val returnedData = data?.getStringExtra("data_return") Toast.makeText(this,returnedData,Toast.LENGTH_SHORT).show() } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.add_item -> Toast.makeText(this, "You clicked Add", Toast.LENGTH_SHORT).show() R.id.remove_item -> Toast.makeText(this, "You clicked Remove", Toast.LENGTH_SHORT).show() } return true } }
firstKotlin/app/src/main/java/com/example/firstkotlin/SecondActivity.kt
460733346
package com.example.firstkotlin import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.second_layout) val button2: Button = findViewById(R.id.button2) button2.setOnClickListener { val data = "你好,页面3" val intent = Intent(this,ThirdActivity::class.java) intent.putExtra("extra_data",data) startActivity(intent) } val buttonFinish: Button = findViewById(R.id.button_finish) buttonFinish.setOnClickListener { val intent = Intent() intent.putExtra("data_return","你好,页面1") setResult(RESULT_OK,intent) finish() } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/ListView/FruitAdapter.kt
4143753059
package com.example.firstkotlin.ListView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import com.example.firstkotlin.R import org.w3c.dom.Text class FruitAdapter(activity: ForthActivity, val resourceId: Int, data: List<Fruit>) : ArrayAdapter<Fruit>(activity, resourceId, data) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { //还是不知道有什么用,就当标准写法了 val view = LayoutInflater.from(context).inflate(resourceId, parent, false) val fruitImage: ImageView = view.findViewById(R.id.fruitImage) val fruitName: TextView = view.findViewById(R.id.fruitName) //获取当前实例 val fruit:Fruit? = getItem(position) if (fruit != null) { fruitImage.setImageResource(fruit.imageId) fruitName.text = fruit.name } return view } }
firstKotlin/app/src/main/java/com/example/firstkotlin/ListView/Fruit.kt
2188565622
package com.example.firstkotlin.ListView class Fruit(val name:String, val imageId: Int)
firstKotlin/app/src/main/java/com/example/firstkotlin/ListView/ForthActivity.kt
1176593025
package com.example.firstkotlin.ListView import android.os.Bundle import android.widget.ArrayAdapter import android.widget.ListView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.firstkotlin.R class ForthActivity : AppCompatActivity() { private val fruitList = ArrayList<Fruit>() // ("鸡蛋", "香肠", "香肠", "", // "虾", "猕猴桃", "柠檬", "葡萄", "牛油果", "西瓜", // "山竹", "肉", "菜", "胡萝卜", "西红柿", "香菇", // "青椒", "玉米", "葱姜蒜", "土豆") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.forth_layout) initFruits() val listView = findViewById<ListView>(R.id.listView) val adapter = FruitAdapter(this, R.layout.fruit_item, fruitList) listView.adapter = adapter listView.setOnItemClickListener { _, _, position, _ -> val fruitPosition = fruitList[position] Toast.makeText(this,fruitPosition.name,Toast.LENGTH_SHORT).show() } } private fun initFruits() { fruitList.add(Fruit("鸡蛋", R.mipmap.jidan)) fruitList.add(Fruit("香肠", R.mipmap.xiangchang)) fruitList.add(Fruit("鱼", R.mipmap.yu)) fruitList.add(Fruit("虾", R.mipmap.xia)) fruitList.add(Fruit("猕猴桃", R.mipmap.mihoutao)) fruitList.add(Fruit("柠檬", R.mipmap.ningmeng)) fruitList.add(Fruit("葡萄", R.mipmap.putao)) fruitList.add(Fruit("牛油果", R.mipmap.niuyouguo)) fruitList.add(Fruit("西瓜", R.mipmap.xigua)) fruitList.add(Fruit("山竹", R.mipmap.shanzhu)) fruitList.add(Fruit("肉", R.mipmap.rou)) fruitList.add(Fruit("菜", R.mipmap.cai)) fruitList.add(Fruit("胡萝卜", R.mipmap.huluobo)) fruitList.add(Fruit("西红柿", R.mipmap.xihongshi)) fruitList.add(Fruit("香菇", R.mipmap.xianggu)) fruitList.add(Fruit("青椒", R.mipmap.qingjiao)) fruitList.add(Fruit("玉米", R.mipmap.yumi)) fruitList.add(Fruit("葱姜蒜", R.mipmap.jiangcongsuan)) fruitList.add(Fruit("土豆", R.mipmap.tudou)) } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Data/Room/UserDao.kt
2900606523
package com.example.firstkotlin.Data.Room import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import androidx.room.Update @Dao interface UserDao { @Insert fun insertUser(user: User): Long @Update fun updateUser(newUser: User) @Query("select * from User") fun loadAllUsers(): List<User> @Query("select * from User where age > :age") fun loadUsersOlderThan(age: Int): List<User> @Delete fun deleteUser(user: User) @Query("delete from User where lastName = :lastName") fun deleteUserByLastName(lastName: String): Int }
firstKotlin/app/src/main/java/com/example/firstkotlin/Data/Room/AppDatabase.kt
1507382296
package com.example.firstkotlin.Data.Room import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(version = 1, entities = [User::class]) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao companion object { private var instance: AppDatabase? = null //@Synchronized 是一个注解,用于实现线程同步。它可以应用于函数或代码块,用于确保在同一时间只能有一个线程访问被注解的函数或代码块 @Synchronized fun getDatabase(context: Context): AppDatabase { instance?.let { return it } return Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "app_database") .build().apply { instance = this } } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Data/Room/User.kt
3538972227
package com.example.firstkotlin.Data.Room import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class User(var firstName: String, var lastName: String, var age: Int) { //使用@PrimaryKey注解将它设为了主键,再把autoGenerate参数指定成true @PrimaryKey(autoGenerate = true) var id: Long = 0 }
firstKotlin/app/src/main/java/com/example/firstkotlin/Data/WritingData.kt
353148252
package com.example.firstkotlin.Data import android.content.Context import android.os.Bundle import android.widget.EditText import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import com.example.firstkotlin.R import java.io.BufferedReader import java.io.BufferedWriter import java.io.IOException import java.io.InputStreamReader import java.io.OutputStreamWriter class WritingData : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_writing_data) val editText1 = findViewById<EditText>(R.id.editText) val inputText = load() if (inputText.isNotEmpty()){ editText1.setText(inputText) // 将光标移动到最后 editText1.setSelection(inputText.length) Toast.makeText(this,"读取数据成功",Toast.LENGTH_SHORT).show() } } override fun onDestroy() { super.onDestroy() val dataInput = findViewById<EditText>(R.id.editText) val inputText = dataInput.text.toString() save(inputText) } /** * 一个写入文件里的方法 * */ private fun save(inputText: String) { try { val output = openFileOutput("data", Context.MODE_PRIVATE) val writer = BufferedWriter(OutputStreamWriter(output)) // use函数,这是Kotlin提供的一个内置扩展函数。 // 它会保证在Lambda表达式中的代码全部执行完之后自动将外层的流关闭,这样就不需要我们再编写一个finally语句,手动去关闭流了,是一个非常好用的扩展函数。 writer.use { it.write(inputText) } } catch (e: IOException) { e.printStackTrace() } } /** * 一个读取文件里的方法 * */ private fun load():String { val content = StringBuilder() try { val input = openFileInput("data") val reader = BufferedReader(InputStreamReader(input)) reader.use { reader.forEachLine { content.append(it) } } }catch (e:IOException){ e.printStackTrace() } return content.toString() } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Data/SqlDataBase/SQLData_MainActivity.kt
593447308
package com.example.firstkotlin.Data.SqlDataBase import android.content.ContentValues import android.os.Bundle import android.widget.Button import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.example.firstkotlin.R class SQLData_MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sqldata_main) //绑定按钮 val createDatabase = findViewById<Button>(R.id.createDatabase) val dbHelper = MyDatabaseHelper(this, "BookStore.db", 2) createDatabase.setOnClickListener { dbHelper.writableDatabase } //绑定按钮 val addData = findViewById<Button>(R.id.addData) addData.setOnClickListener { val db = dbHelper.writableDatabase val values1 = ContentValues().apply { //开始组装第一条数据 put("name", "The Da Vinci Code") put("author", "John Johnson") put("pages", 454) put("price", 16.96) } //插入第一条数据 db.insert("Book", null, values1) val values2 = ContentValues().apply { put("name", "The Lost Symbol") put("author", "Dan") put("pages", 510) put("price", 19.95) } db.insert("Book", null, values2) } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Data/SqlDataBase/MyDatabaseHelper.kt
1357139453
package com.example.firstkotlin.Data.SqlDataBase import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.widget.Toast class MyDatabaseHelper(val context: Context, name: String, version: Int) : SQLiteOpenHelper(context, name, null, version) { private val createBook = "create table Book (" + " id integer primary key autoincrement," + "author text," + "price real," + "pages integer," + "name text)" private val category = "create table Category (" + "id integer primary key autoincrement," + "category_name text," + "category_code integer)" override fun onCreate(db: SQLiteDatabase) { db.execSQL(createBook) db.execSQL(category) Toast.makeText(context, "Create succeeded", Toast.LENGTH_SHORT).show() } override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) { db.execSQL("drop table if exists Book") db.execSQL("drop table if exists Category") onCreate(db) } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Data/SharedPreferencesTest.kt
2805989570
package com.example.firstkotlin.Data import android.content.Context import android.os.Bundle import android.util.Log import android.widget.Button import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.example.firstkotlin.R class SharedPreferencesTest : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_shared_preferences_test) //存储数据 val saveBtn = findViewById<Button>(R.id.saveButton) saveBtn.setOnClickListener{ val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit() editor.putString("name","你爹") editor.putInt("age",28) editor.putBoolean("married",false) editor.apply() } //读取数据 val restoreBtn = findViewById<Button>(R.id.restoreButton) restoreBtn.setOnClickListener{ val prefs = getSharedPreferences("data",Context.MODE_PRIVATE) val name = prefs.getString("name","") val age = prefs.getInt("age",0) val married = prefs.getBoolean("married",false) Log.d("SharedPreferencesTest","name is $name") Log.d("SharedPreferencesTest","age is $age") Log.d("SharedPreferencesTest","married is $married") } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/BroadcastReceiver/MyBroadcastReceiver.kt
3312730221
package com.example.firstkotlin.BroadcastReceiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast class MyBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show() } }
firstKotlin/app/src/main/java/com/example/firstkotlin/BroadcastReceiver/BroadcastTest.kt
160734710
package com.example.firstkotlin.BroadcastReceiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.widget.Button import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import com.example.firstkotlin.R class BroadcastTest : AppCompatActivity() { lateinit var timeChangeReceiver: TimeChangeReceiver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_broadcast_test) val sentBC = findViewById<Button>(R.id.button) sentBC.setOnClickListener { val intent =Intent("com.example.broadcasttest.MY_BROADCAST") intent.setPackage(packageName) sendBroadcast(intent) } // //BroadcastReceiver想要监听什么广播,就在这里添加相应的action // val intentFilter = IntentFilter() // intentFilter.addAction("android.intent.action.TIME_TICK") // // timeChangeReceiver = TimeChangeReceiver() // registerReceiver(timeChangeReceiver, intentFilter) } //在注册广播接收器之后,需要在不再需要接收广播消息时调用 unregisterReceiver() 方法来取消注册,以避免内存泄漏 //成对存在 override fun onDestroy() { super.onDestroy() unregisterReceiver(timeChangeReceiver) } inner class TimeChangeReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Toast.makeText(context, "时间刷新了", Toast.LENGTH_SHORT).show() } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Login/BaseActivity.kt
724712306
package com.example.firstkotlin.Login import android.app.AlertDialog import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Bundle import androidx.appcompat.app.AppCompatActivity open class BaseActivity : AppCompatActivity() { lateinit var recevier: ForceOfflineReceiver override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) ActivityCollector.addActivity(this) } override fun onDestroy() { super.onDestroy() ActivityCollector.removeActivity(this) } override fun onResume() { super.onResume() val intentFilter = IntentFilter() intentFilter.addAction("com.example.broadcastbestpractice.FORCE_OFFLINE") recevier = ForceOfflineReceiver() registerReceiver(recevier, intentFilter) } //始终需要保证只有处于栈顶的Activity才能接收到这条强制下线广播 override fun onPause() { super.onPause() unregisterReceiver(recevier) } inner class ForceOfflineReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { AlertDialog.Builder(context).apply { setTitle("强制退出") setMessage("你被强制登出下线了") setCancelable(false) setPositiveButton("OjbK") { _, _ -> //销毁所有的Activity ActivityCollector.finishAll() val i = Intent(context, LoginActivity::class.java) context.startActivity(i) } show() } } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Login/LoginMainActivity.kt
3460956407
package com.example.firstkotlin.Login import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.example.firstkotlin.R class LoginMainActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login_main) //强制下线功能 val forceOfflineBtn = findViewById<Button>(R.id.forceOffline) forceOfflineBtn.setOnClickListener { val intent = Intent("com.example.broadcastbestpractice.FORCE_OFFLINE") sendBroadcast(intent) } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Login/LoginActivity.kt
3082184721
package com.example.firstkotlin.Login import android.content.Context import android.content.Intent import android.os.Bundle import android.widget.Button import android.widget.CheckBox import android.widget.EditText import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.example.firstkotlin.MainActivity import com.example.firstkotlin.R class LoginActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) //声明那些控件 val loginBtn = findViewById<Button>(R.id.login) val accountEdit = findViewById<EditText>(R.id.accountEdit) val passwordEdit = findViewById<EditText>(R.id.passwordEdit) val cbRememberPass = findViewById<CheckBox>(R.id.rememberPass) val prefs = getPreferences(Context.MODE_PRIVATE) val isRemember = prefs.getBoolean("remember_password",false) if(isRemember){ //将账号密码设置到文本框中 val account = prefs.getString("account","") val password = prefs.getString("password","") accountEdit.setText(account) passwordEdit.setText(password) //设置选项为勾选 cbRememberPass.isChecked = true } //登录的功能 loginBtn.setOnClickListener { val account = accountEdit.text.toString() val password = passwordEdit.text.toString() // 如果账号是Admin 且密码是123456,就认为登录成功 if (account == "Admin" && password == "123456") { val editor = prefs.edit() if(cbRememberPass.isChecked){ editor.putBoolean("remember_password",true) editor.putString("account",account) editor.putString("password",password) }else{ editor.clear() } //提交内容进行保存 editor.apply() //设置登录后的跳转 val intent = Intent(this,LoginMainActivity::class.java) startActivity(intent) finish() }else{ Toast.makeText(this,"wrongPassword",Toast.LENGTH_SHORT).show() } } } }
firstKotlin/app/src/main/java/com/example/firstkotlin/Login/ActivityCollector.kt
3979812481
package com.example.firstkotlin.Login import android.app.Activity object ActivityCollector { private val activities = ArrayList<Activity>() fun addActivity(activity: Activity) { activities.add(activity) } fun removeActivity(activity: Activity) { activities.remove(activity) } fun finishAll() { for (activity in activities) { if (!activity.isFinishing) { activity.finish() } } activities.clear() } }
Grader_T/app/src/androidTest/java/com/example/grader_t/ExampleInstrumentedTest.kt
4145182736
package com.example.grader_t 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("com.example.grader_t", appContext.packageName) } }
Grader_T/app/src/test/java/com/example/grader_t/ExampleUnitTest.kt
2712391639
package com.example.grader_t 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) } }
Grader_T/app/src/main/java/com/example/grader_t/MainActivity.kt
2808644347
package com.example.grader_t import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
Grader_T/app/src/main/java/com/example/grader_t/Splash_screen.kt
1754931670
package com.example.grader_t import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class Splash_screen : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) } }
Top-Trumps/Android/TopTrumps/app/src/androidTest/java/dev/jules/toptrumps/ExampleInstrumentedTest.kt
3302696426
package dev.jules.toptrumps 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("dev.jules.toptrumps", appContext.packageName) } }
Top-Trumps/Android/TopTrumps/app/src/test/java/dev/jules/toptrumps/ExampleUnitTest.kt
1444470370
package dev.jules.toptrumps 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) } }
Top-Trumps/Android/TopTrumps/app/src/main/java/dev/jules/toptrumps/ui/theme/Color.kt
1318664070
package dev.jules.toptrumps.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
Top-Trumps/Android/TopTrumps/app/src/main/java/dev/jules/toptrumps/ui/theme/Theme.kt
834322393
package dev.jules.toptrumps.ui.theme import android.app.Activity import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun TopTrumpsTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Top-Trumps/Android/TopTrumps/app/src/main/java/dev/jules/toptrumps/ui/theme/Type.kt
3906453167
package dev.jules.toptrumps.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Top-Trumps/Android/TopTrumps/app/src/main/java/dev/jules/toptrumps/MainActivity.kt
381616722
package dev.jules.toptrumps import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp import dev.jules.toptrumps.ui.theme.TopTrumpsTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TopTrumpsTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Body() } } } } } @Composable fun Body() { Scaffold( topBar = { Surface(color = Color.Green, modifier = Modifier.fillMaxWidth()) { Text("Welcome", fontSize = 18.sp) } }, floatingActionButton = { FloatingActionButton(onClick = { /*TODO*/ }) { Text("Test BTN") } } ) { innerPadding -> Text("Test Content", modifier = Modifier.padding(innerPadding)) LazyColumn { } } } @Preview(showBackground = true, showSystemUi = true) @Composable fun BodyPreview() { Body() }
Week2_wzy/app/src/androidTest/java/com/example/week2_wzy/ExampleInstrumentedTest.kt
1818019122
package com.example.week2_wzy 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("com.example.week2_wzy", appContext.packageName) } }
Week2_wzy/app/src/test/java/com/example/week2_wzy/ExampleUnitTest.kt
1260794438
package com.example.week2_wzy 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) } }
Week2_wzy/app/src/main/java/com/example/week2_wzy/home/HomeModel.kt
2779845328
package com.example.week2_wzy.home import androidx.lifecycle.MutableLiveData import com.example.week2_wzy.base.BaseModel import com.example.week2_wzy.entity.GoodsEntity import io.reactivex.internal.operators.maybe.MaybeDoAfterSuccess class HomeModel :BaseModel(){ val repo=HomeRepo() val success=MutableLiveData<GoodsEntity>() val field=MutableLiveData<String>() fun getGood(category:Int,currentPage:Int,pageSize:Int){ repo.getGoods(category,currentPage,pageSize,success,field) } // repo.getGoods(category,currentPage,pageSize,success,field) }
Week2_wzy/app/src/main/java/com/example/week2_wzy/home/HomeRepo.kt
1194289271
package com.example.week2_wzy.home import androidx.lifecycle.MutableLiveData import com.example.week2_wzy.base.BaseRepo import com.example.week2_wzy.entity.GoodsEntity import io.reactivex.Observer import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers class HomeRepo:BaseRepo() { fun getGoods(category_id :Int, currentPage:Int, pageSize:Int, success:MutableLiveData<GoodsEntity>, field:MutableLiveData<String>){ api().getGoods(category_id,currentPage,pageSize) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(object :Observer<GoodsEntity>{ override fun onSubscribe(d: Disposable) { } override fun onError(e: Throwable) { // field.value=e.message } override fun onComplete() { } override fun onNext(t: GoodsEntity) { success.value=t } }) } }
Week2_wzy/app/src/main/java/com/example/week2_wzy/MainActivity.kt
1702857333
package com.example.week2_wzy import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import com.example.week2_wzy.adapter.GoodsAdapter import com.example.week2_wzy.base.BaseActivity import com.example.week2_wzy.databinding.ActivityMainBinding import com.example.week2_wzy.entity.Data import com.example.week2_wzy.home.HomeModel class MainActivity : BaseActivity<ActivityMainBinding>() { lateinit var hm:HomeModel lateinit var adapter:GoodsAdapter val list= mutableListOf<Data>() override fun initdata() { hm=ViewModelProvider(this)[HomeModel::class.java] hm.getGood(0,1,10) hm.success.observe(this){ list.addAll(it.data) adapter.notifyDataSetChanged() } } override fun initview() { db.rv.layoutManager=GridLayoutManager(this,2) adapter=GoodsAdapter(list) db.rv.adapter=adapter //点击事件 adapter.setOnItemClickListener { adapter, view, position -> intent=Intent(this,XqActivity::class.java) startActivity(intent) } } override fun bindLayout(): Int=R.layout.activity_main }
Week2_wzy/app/src/main/java/com/example/week2_wzy/entity/GoodsEntity.kt
2258061851
package com.example.week2_wzy.entity data class GoodsEntity( val code: Int, val `data`: List<Data>, val message: String ) data class Data( val bannerList: List<String>, val category_id: Int, val goods_attribute: String, val goods_banner: String, val goods_code: String, val goods_default_icon: String, val goods_default_price: Int, val goods_desc: String, val goods_detail_one: String, val goods_detail_two: String, val goods_sales_count: Int, val goods_stock_count: Int, val id: Int )
Week2_wzy/app/src/main/java/com/example/week2_wzy/XqActivity.kt
3154300406
package com.example.week2_wzy import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.GridLayoutManager import com.example.week2_wzy.adapter.GoodsAdapter import com.example.week2_wzy.base.BaseActivity import com.example.week2_wzy.databinding.ActivityXqBinding import com.example.week2_wzy.entity.Data import com.example.week2_wzy.home.HomeModel class XqActivity :BaseActivity<ActivityXqBinding>() { // lateinit var hm: HomeModel // lateinit var adapter: GoodsAdapter // val list= mutableListOf<Data>() // override fun initdata() { // // // override fun initview() { // // } // // override fun bindLayout(): Int=R.layout.activity_xq override fun initdata() { } override fun initview() { } override fun bindLayout(): Int=R.layout.activity_xq }
Week2_wzy/app/src/main/java/com/example/week2_wzy/adapter/GoodsAdapter.kt
1393554826
package com.example.week2_wzy.adapter import com.bumptech.glide.Glide import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.viewholder.BaseViewHolder import com.example.week2_wzy.R import com.example.week2_wzy.entity.Data class GoodsAdapter (goodlist:MutableList<Data>):BaseQuickAdapter<Data,BaseViewHolder>(R.layout.item,goodlist){ override fun convert(helper: BaseViewHolder, item: Data) { Glide.with(context).load(item.goods_default_icon).into(helper.getView(R.id.iv)) helper.setText(R.id.tv,"${item.goods_default_price}元") } }
Week2_wzy/app/src/main/java/com/example/week2_wzy/base/net/Api.kt
1319506254
package com.example.week2_wzy.base.net import com.example.week2_wzy.entity.GoodsEntity import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.Query interface Api { @GET("/goods/info") fun getGoods(@Query("category_id")category_id :Int, @Query("currentPage")currentPage :Int, @Query("pageSize")pageSize :Int, ):Observable<GoodsEntity> }
Week2_wzy/app/src/main/java/com/example/week2_wzy/base/net/RetrofitManager.kt
3722569287
package com.example.week2_wzy.base.net import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit class RetrofitManager { companion object{ fun getRetrofit():Retrofit{ val okHttpClient=OkHttpClient.Builder() .writeTimeout(30,TimeUnit.SECONDS) .readTimeout(30,TimeUnit.SECONDS) .callTimeout(30,TimeUnit.SECONDS) .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) val retrofit=Retrofit.Builder() .baseUrl("http://10.161.9.80:7012") .client(okHttpClient.build()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) return retrofit.build() } } }
Week2_wzy/app/src/main/java/com/example/week2_wzy/base/BaseActivity.kt
112059805
package com.example.week2_wzy.base import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding abstract class BaseActivity <VDB:ViewDataBinding>:AppCompatActivity(){ lateinit var db:VDB override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) db=DataBindingUtil.setContentView(this,bindLayout()) initview() initdata() } abstract fun initdata() abstract fun initview() abstract fun bindLayout(): Int }
Week2_wzy/app/src/main/java/com/example/week2_wzy/base/BaseRepo.kt
2266796044
package com.example.week2_wzy.base import com.example.week2_wzy.base.net.Api import com.example.week2_wzy.base.net.RetrofitManager open class BaseRepo { fun api():Api=RetrofitManager.getRetrofit().create(Api::class.java) }
Week2_wzy/app/src/main/java/com/example/week2_wzy/base/BaseModel.kt
2386118509
package com.example.week2_wzy.base import androidx.lifecycle.ViewModel open class BaseModel:ViewModel() { }
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/extension/ExtensionLoader.kt
2495009216
package tanoshi.multiplatform.shared.extension import tanoshi.multiplatform.common.extension.interfaces.Extension expect class ExtensionLoader { val loadedExtensionClasses : HashMap< String , Extension > fun loadTanoshiExtension( vararg tanoshiExtensionFile : String ) }
Tanoshi-Multiplatform/composeApp/src/commonMain/kotlin/tanoshi/multiplatform/shared/extension/ExtensionManager.kt
1411557959
package tanoshi.multiplatform.shared.extension import java.io.File import java.io.FileInputStream expect class ExtensionManager { val extensionLoader : ExtensionLoader fun install( extensionId : String , fileInputStream : FileInputStream ) fun install( extensionId: String , file : File ) fun uninstall( extensionId: String ) }