content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.shopevoucherapp.presentation.AccountUser import android.content.Context import android.util.Log import android.widget.Toast import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.shopevoucherapp.data.Local.AuthPreferences import com.example.shopevoucherapp.data.remote.response.UserResponse.User import com.example.shopevoucherapp.domain.use_case.GetUserUseCase import com.example.shopevoucherapp.domain.use_case.ResetPasswordUseCase import com.example.shopevoucherapp.util.Resources import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class AccountUserViewModel @Inject constructor( private val getUserUseCase: GetUserUseCase, private val authPreferences: AuthPreferences, private val resetPasswordUseCase: ResetPasswordUseCase ) : ViewModel() { private val _userInfo = mutableStateOf(User()) val userInfo : State<User> = _userInfo init { viewModelScope.launch { getUser() } } suspend fun resetPassword(onNavigate: () -> Unit, context : Context){ Log.d("resetpassword",userInfo.value.email.toString() ) when(val res = userInfo.value.email?.let { resetPasswordUseCase(it) }){ is Resources.Success -> { Toast.makeText(context, "${res.data.msg}", Toast.LENGTH_LONG).show() Log.d("resetpassword", res.data.msg.toString()) onNavigate() } is Resources.Error -> { Log.d("resetpassword", "error") } else -> { } } } private suspend fun getUser(){ when(val res = getUserUseCase()){ is Resources.Success ->{ _userInfo.value = res.data Log.d("userInfo", userInfo.value.toString()) } is Resources.Error -> { Log.d("userInfo", res.errors.toString()) } else ->{ } } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/AccountUser/AccountUserViewModel.kt
4262629632
package com.example.shopevoucherapp.presentation.navigation import android.content.Intent import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navArgument import androidx.navigation.navDeepLink import com.example.shopevoucherapp.presentation.AccountUser.AccountUserScreen import com.example.shopevoucherapp.presentation.AccountUser.InfoApp.AboutUsScreen import com.example.shopevoucherapp.presentation.AccountUser.InfoApp.AccountAndSecurityScreen import com.example.shopevoucherapp.presentation.AccountUser.InfoApp.HelpScreen import com.example.shopevoucherapp.presentation.AccountUser.InfoApp.UserInfo.LoginAndSecurity import com.example.shopevoucherapp.presentation.AccountUser.InfoApp.UserInfo.ResetPasswordScreen import com.example.shopevoucherapp.presentation.AccountUser.InfoApp.UserInfo.UserInfo import com.example.shopevoucherapp.presentation.Authentication.Login.LoginScreen import com.example.shopevoucherapp.presentation.Authentication.SignIn.RegisterScreen import com.example.shopevoucherapp.presentation.Authentication.UpdatePassword.ForgotPasswordScreen import com.example.shopevoucherapp.presentation.Authentication.UpdatePassword.TypeNewPasswordScreen import com.example.shopevoucherapp.presentation.Coupons.CouponsScreen import com.example.shopevoucherapp.presentation.FunctionScreen.RefundScreen.RefundScreen import com.example.shopevoucherapp.presentation.Home.HomeScreen import com.example.shopevoucherapp.presentation.MainViewModel import com.example.shopevoucherapp.presentation.Posts.PostsScreen import com.example.shopevoucherapp.presentation.Screen.Screen @RequiresApi(Build.VERSION_CODES.O) @Composable fun NavigationGraph( navController: NavHostController, pd : PaddingValues, mainViewModel: MainViewModel = hiltViewModel() ){ val startDestination = remember { mutableStateOf(Screen.FunScreen.Login.route) } if(mainViewModel.tokenState.value != ""){ startDestination.value = Screen.BottomBar.Home.route } NavHost(navController = navController , startDestination = startDestination.value){ composable(Screen.BottomBar.Home.route){ HomeScreen(navController) } composable(Screen.BottomBar.Coupons.route){ CouponsScreen() } composable(Screen.BottomBar.Posts.route){ PostsScreen(navController) } composable(Screen.FunScreen.RefundDetail.route){ RefundScreen(navController) } composable(Screen.BottomBar.Account.route){ AccountUserScreen(navController) } //Function Screen composable( route = Screen.FunScreen.Login.route, // deepLinks = listOf( // navDeepLink { // uriPattern = "https://www.magiamgia.pro/reset-password/{id}" // action = Intent.ACTION_VIEW // } // ), // arguments = listOf( // navArgument("id"){ // type = NavType.IntType // defaultValue = -1 // } // ) ){ LoginScreen(navController) } composable(Screen.FunScreen.Register.route){ RegisterScreen(navController) } composable(Screen.FunScreen.TypeNewPassword.route){ TypeNewPasswordScreen(navController) } composable(Screen.FunScreen.ForgotPassword.route){ ForgotPasswordScreen(navController) } //AboutApp Screen composable(Screen.AboutApp.AccountAndSecurity.route){ AccountAndSecurityScreen(navController) } composable(Screen.AboutApp.AboutUs.route){ AboutUsScreen(navController) } composable(Screen.AboutApp.Help.route){ HelpScreen(navController) } composable(Screen.AboutApp.AccountInfo.route){ UserInfo(navController) } composable(Screen.AboutApp.LoginAndSecurity.route){ LoginAndSecurity(navController) } composable(Screen.AboutApp.UpdatePassword.route){ ResetPasswordScreen(navController) } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/navigation/NavigationGraph.kt
3943837918
package com.example.shopevoucherapp.presentation.Component import android.transition.Slide import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PageSize import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import coil.compose.AsyncImage import coil.compose.rememberAsyncImagePainter import coil.compose.rememberImagePainter import coil.request.ImageRequest import coil.size.Size import com.example.shopevoucherapp.R import com.example.shopevoucherapp.domain.model.Post import com.example.shopevoucherapp.presentation.Home.HomeViewModel import kotlinx.coroutines.delay import java.nio.channels.AsynchronousByteChannel @OptIn(ExperimentalFoundationApi::class) @Composable fun SlidePost(data : List<Post>){ val paperState = rememberPagerState(pageCount = {data.size}) HorizontalPager( state = paperState ) {index -> Box(modifier = Modifier.fillMaxWidth()){ Image( painter = rememberAsyncImagePainter(model =data[index].img ), contentDescription = null, modifier = Modifier .height(200.dp) .fillMaxWidth() .aspectRatio(1f) ) } } LaunchedEffect(key1 = true) { val startTime = System.currentTimeMillis() while (true) { val elapsedTime = System.currentTimeMillis() - startTime if (elapsedTime >= 3000) { paperState.animateScrollToPage((paperState.currentPage + 1)% paperState.pageCount) } delay(2000) } } } @Preview(showBackground = true) @Composable fun fgdsgsdf(){ SlidePost(listOf()) }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Component/SlidePost.kt
4116482852
package com.example.shopevoucherapp.presentation.Component import android.app.AlertDialog import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import com.example.shopevoucherapp.R @Composable fun AlertDialog( onDismiss: () -> Unit ){ AlertDialog( onDismissRequest = { /*TODO*/ }, confirmButton = { Button(onClick = { /*TODO*/ }) { Text( text = "Xác nhận", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)) ) ) } }, text = { Text(text = "Đăng kí thành công!") } ) }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Component/AlertDialog.kt
911922699
package com.example.shopevoucherapp.presentation.Component import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource 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.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.example.shopevoucherapp.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun TopAppBarView(type : String, navController : NavController){ TopAppBar( modifier = Modifier .fillMaxWidth() // .padding(top = 20.dp) .height(50.dp), title = { Row( modifier = Modifier .fillMaxWidth() .fillMaxHeight() .padding(start = 16.dp, end = 16.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { if (type == "main") { Image( painter = painterResource(id = R.drawable.logo), contentDescription = "App", modifier = Modifier .wrapContentSize() .offset(x = -20.dp) .clickable { }, contentScale = ContentScale.Fit ) IconButton( onClick = { }, modifier = Modifier ) { Icon( painter = painterResource(id = R.drawable.search), contentDescription = "Search", modifier = Modifier.size(20.dp) ) } } else { IconButton( onClick = { navController.navigateUp() }, modifier = Modifier.offset(x = -25.dp) ) { Icon( painter = painterResource(id = R.drawable.arrow_left_solid), contentDescription = "BackPress", modifier = Modifier .size(25.dp) .width(30.dp) ) } Text( text = type, style = TextStyle( fontFamily = FontFamily.SansSerif , fontWeight = FontWeight.Bold, fontSize = 20.sp ) ) IconButton(onClick = { }) { Icon( painter = painterResource(id = R.drawable.three_dot), contentDescription = "BackPress", modifier = Modifier .size(20.dp) .width(30.dp) ) } } } }) }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Component/TopAppBar.kt
4062879298
package com.example.shopevoucherapp.presentation.Component.LoadingBtnCustom import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.StartOffset import androidx.compose.animation.core.animate import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Button import androidx.compose.material.ButtonColors import androidx.compose.material.ButtonDefaults import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp private const val IndicatorSize = 3 private const val NumIndicators = 3 enum class AnimationType { Bounce, Fade, } private val AnimationType.animationDuration: Int get() = when (this) { AnimationType.Bounce -> 300 AnimationType.Fade -> 600 } private val AnimationType.animationDelay: Int get() = animationDuration / NumIndicators private val AnimationType.initialValue: Float get() = when (this) { AnimationType.Bounce -> IndicatorSize / 2f AnimationType.Fade -> 1f } private val AnimationType.targetValue: Float get() = when (this) { AnimationType.Bounce -> -IndicatorSize / 2f AnimationType.Fade -> .2f } @Composable fun LoadingButtonIndicator() { var loading by remember { mutableStateOf(false) } LoadingButton( onClick = { loading = !loading }, loading = loading, ) { Text(text = "Refresh") } } @Composable private fun LoadingIndicator( animating: Boolean, modifier: Modifier = Modifier, color: Color = MaterialTheme.colors.primary, indicatorSpacing: Dp = 1.dp, animationType: AnimationType ) { val animatedValues = List(IndicatorSize) { index -> var animatedValue by remember(key1 = animating, key2 = animationType) { mutableStateOf(0f) } LaunchedEffect(key1 = animating, key2 = animationType) { if (animating) { animate( initialValue = animationType.initialValue, targetValue = animationType.targetValue, animationSpec = infiniteRepeatable( animation = tween(durationMillis = animationType.animationDuration), repeatMode = RepeatMode.Reverse, initialStartOffset = StartOffset(animationType.animationDelay * index), ), ) { value, _ -> animatedValue = value } } } animatedValue } Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically) { animatedValues.forEach { animatedValue -> LoadingDot( modifier = Modifier .padding(horizontal = indicatorSpacing) .width(IndicatorSize.dp) .aspectRatio(1f) .then( when (animationType) { AnimationType.Bounce -> Modifier.offset(y = animatedValue.dp) AnimationType.Fade -> Modifier.graphicsLayer { alpha = animatedValue } } ), color = color, ) } } } @Composable fun LoadingButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, loading: Boolean = false, colors: ButtonColors = ButtonDefaults.buttonColors(), indicatorSpacing: Dp = 1.dp, content: @Composable () -> Unit, ) { val contentAlpha by animateFloatAsState(targetValue = if (loading) 0f else 1f) val loadingAlpha by animateFloatAsState(targetValue = if (loading) 1f else 0f) Button( onClick = onClick, modifier = modifier, enabled = enabled, colors = colors, ) { Box( contentAlignment = Alignment.Center, ) { LoadingIndicator( animating = loading, modifier = Modifier.graphicsLayer { alpha = loadingAlpha }, color = colors.contentColor(enabled = enabled).value, indicatorSpacing = indicatorSpacing, animationType = AnimationType.Bounce ) Box( modifier = Modifier .graphicsLayer { alpha = contentAlpha } ) { content() } } } } @Composable private fun LoadingDot( color: Color, modifier: Modifier = Modifier, ) { Box( modifier = modifier .clip(shape = CircleShape) .background(color = color) ) }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Component/LoadingBtnCustom/LoadingIndicator.kt
840138345
package com.example.shopevoucherapp.presentation.Component.LoadingBtnCustom import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.res.colorResource import androidx.compose.ui.unit.dp import com.example.shopevoucherapp.R @Composable fun Indicator(active : Boolean){ val color = if(active) colorResource(id = R.color.schedule_primary) else colorResource(id = R.color.schedule_second) val size = if(active) 10.dp else 5.dp val shape = if(active) CircleShape else CircleShape Box( modifier = Modifier .clip(shape) .background(color) .size(size) ) }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Component/LoadingBtnCustom/Indicator.kt
3197296016
package com.example.shopevoucherapp.presentation.Coupons.component data class CateroriesData( val img : Int ?= 0, val title : String? = "", val type : String? ="toan-san" )
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Coupons/component/CateroriesData.kt
3632913758
package com.example.shopevoucherapp.presentation.Coupons.component import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import coil.ImageLoader import coil.compose.AsyncImage import coil.compose.rememberAsyncImagePainter import coil.decode.SvgDecoder import com.example.shopevoucherapp.R @Composable fun CateroriesCouponView(data : CateroriesData, onClick : () -> Unit, selectedIndex : Boolean){ val context = LocalContext.current val imageLoader = ImageLoader.Builder(context) .components { add(SvgDecoder.Factory()) } .build() val background = if(selectedIndex) CardDefaults.cardColors(Color.LightGray) else CardDefaults.cardColors(Color.White) Card ( elevation = CardDefaults.cardElevation(1.dp), modifier = Modifier .wrapContentSize() .padding(10.dp) .clickable { onClick() } , colors = background ){ Column ( modifier = Modifier .background(color = Color.White) .padding(5.dp) .width(80.dp) , verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ){ data.img?.let { painterResource(id = it) }?.let { Image( painter = it, contentDescription = null , modifier = Modifier .width(40.dp) .clip(RoundedCornerShape(10.dp)) .height(60.dp), contentScale = ContentScale.Fit ) } data.title?.let { Text( text = it, modifier = Modifier.padding(5.dp), style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), fontSize = 10.sp, color = Color.Black ) ) } } }} @Preview(showBackground = true) @Composable fun sfgsdg(){ CateroriesCouponView(CateroriesData( img = R.drawable.money, title = "Thời Trang"), {}, false ) }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Coupons/component/CateroriesCouponView.kt
4266564295
package com.example.shopevoucherapp.presentation.Coupons import android.util.Log import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.shopevoucherapp.domain.model.Coupon import com.example.shopevoucherapp.domain.model.Post import com.example.shopevoucherapp.domain.use_case.GetCouponsUseCase import com.example.shopevoucherapp.domain.use_case.GetPostsUseCase import com.example.shopevoucherapp.util.Resources import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CouponsViewModel @Inject constructor( private val getCouponsUseCase: GetCouponsUseCase ) : ViewModel() { private val _coupons = mutableStateListOf<Coupon>() val coupons: List<Coupon> = _coupons private val _isLoading = mutableStateOf(false) val isLoading : State<Boolean> = _isLoading init { viewModelScope.launch { getCoupons("toan-san") } } suspend fun getCoupons(type : String) { _isLoading.value = true when (val response = getCouponsUseCase(type)) { is Resources.Loading -> { Log.d("CouponScreen", "getUCoupons: Loading") } is Resources.Success -> { _isLoading.value = false _coupons.clear() val couponsRes = response.data.toCouponList() _coupons.addAll(couponsRes) Log.d("CouponScreen", "getUCoupons: $couponsRes") } is Resources.Error -> { Log.d("CouponScreen", "getUCoupons: ${response.errors}") } } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Coupons/CouponsViewModel.kt
1334562725
package com.example.shopevoucherapp.presentation.Coupons import android.util.Log import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Tab import androidx.compose.material3.TabRow import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import com.example.shopevoucherapp.presentation.Coupons.component.CateroriesData import com.example.shopevoucherapp.R import com.example.shopevoucherapp.presentation.Coupons.component.CateroriesCouponView import com.example.shopevoucherapp.presentation.Home.Component.CouponItem import kotlinx.coroutines.delay import kotlinx.coroutines.launch @OptIn(ExperimentalFoundationApi::class) @Composable fun CouponsScreen( couponsViewModel: CouponsViewModel = hiltViewModel() ){ Log.d("StartApp", "Coupon") val isLoading = couponsViewModel.isLoading var coupons = couponsViewModel.coupons Log.d("CouponScreen", coupons.toString()) Log.d("LogReload", "coupon") val selectedIndex = remember{ mutableIntStateOf(0) } val pagerState = rememberPagerState(pageCount = { listCategories.size}) val scope = rememberCoroutineScope() LaunchedEffect(selectedIndex){ pagerState.animateScrollToPage( selectedIndex.intValue, ) } LaunchedEffect(pagerState.currentPage){ selectedIndex.intValue = pagerState.currentPage } Column( modifier = Modifier .padding(top = 50.dp, bottom = 50.dp) .verticalScroll(rememberScrollState()) ){ LazyRow( modifier = Modifier .fillMaxWidth() .clip(RoundedCornerShape(10.dp)) .padding(top = 20.dp) ){ itemsIndexed(listCategories){index, item -> CateroriesCouponView(data = item, onClick = { scope.launch { item.type?.let { couponsViewModel.getCoupons(it) } } }, selectedIndex = index == selectedIndex.intValue ) } } // HorizontalPager( // state = pagerState, // userScrollEnabled = false // ) {index-> Column( modifier = Modifier .fillMaxSize() , verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ){ if(isLoading.value){ CircularProgressIndicator( modifier = Modifier .width(20.dp) .height(20.dp), strokeWidth = 1.dp, color = colorResource(id = R.color.schedule_primary) ) }else{ if(coupons.isEmpty()){ Text( text = "Không tìm thấy voucher nào trên Shopee liên quan đến danh mục này", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), fontSize = 15.sp, color = colorResource(id = R.color.schedule_primary), textAlign = TextAlign.Center ), modifier = Modifier.padding(10.dp) ) } coupons.forEachIndexed{i, item -> CouponItem(data = item) } } } } // } } val listCategories = listOf( CateroriesData( img = R.drawable.all_pig, title = "Tất Cả", type = "toan-san" ), CateroriesData( img = R.drawable.thoitrang, title = "Thời trang", type = "thoi-trang" ), CateroriesData( img = R.drawable.deintu, title = "Điện tử", type = "dien-tu" ), CateroriesData( img = R.drawable.vegetables, title = "Tiêu dùng", type ="tieu-dung" ), CateroriesData( img =R.drawable.money, title = "0 Đồng", type ="khong-dong" ), ) @Preview(showBackground = true) @Composable fun sdhkfhsdf(){ CouponsScreen() }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Coupons/CouponsScreen.kt
4048169420
package com.example.shopevoucherapp.presentation.Screen import androidx.annotation.DrawableRes import com.example.shopevoucherapp.R sealed class Screen(val title: String, val route: String) { sealed class BottomBar(val bTitle: String, val bRouter: String, @DrawableRes val icon: Int) : Screen(bTitle, bRouter) { object Home : BottomBar( bTitle = "Home", bRouter = "home", R.drawable.house_solid ) object Coupons : BottomBar( bTitle = "Library", bRouter = "library", R.drawable.ticket_solid ) object Posts : BottomBar( bTitle = "Create", bRouter = "create", R.drawable.newspaper_solid ) object Account : BottomBar( bTitle = "Account", bRouter = "account", R.drawable.user_solid ) } sealed class FunScreen(val fTitle: String, val fRouter: String, @DrawableRes val icon: Int) : Screen(fTitle, fRouter){ object RefundDetail : FunScreen( fTitle = "RefundDetail", fRouter = "refunddetail", R.drawable.newspaper_solid ) object Login : FunScreen( fTitle = "Login", fRouter = "login", R.drawable.newspaper_solid ) object Register : FunScreen( fTitle = "Register", fRouter = "register", R.drawable.newspaper_solid ) object TypeNewPassword : FunScreen( fTitle = "TypeNewPassword", fRouter = "typenewpassword", R.drawable.newspaper_solid ) object ForgotPassword : FunScreen( fTitle = "ForgotPassword", fRouter = "forgotpassword", R.drawable.newspaper_solid ) } sealed class AboutApp(val aTitle: String, val aRouter: String, @DrawableRes val icon: Int) : Screen(aTitle, aRouter){ object AccountAndSecurity : AboutApp( aTitle = "Tài khoản & Bảo mật", aRouter = "accountandsecurity", R.drawable.user_solid ) object AboutUs : AboutApp( aTitle = "Cách hoạt động", aRouter = "aboutus", R.drawable.warning ) object Help : AboutApp( aTitle = "Hỗ trợ", aRouter = "help", R.drawable.headset_solid ) object AccountInfo : AboutApp( aTitle = "Thông tin cá nhân", aRouter = "accountinfo", R.drawable.user_circle ) object LoginAndSecurity : AboutApp( aTitle = "Đăng Nhập & Bảo Mật", aRouter = "security", R.drawable.key_solid ) object UpdatePassword : AboutApp( aTitle = "Cập nhật mật khẩu", aRouter = "updatepassword", R.drawable.update ) object Logout : AboutApp( aTitle = "Logout", aRouter = "login", R.drawable.logout ) object InviteFriend : AboutApp( aTitle = "Mã giới thiệu", aRouter = "invited", R.drawable.user_plus_solid ) object Gift : AboutApp( aTitle = "Thưởng", aRouter = "gift", R.drawable.gift_solid ) } } val listModal = listOf( Screen.BottomBar.Home, Screen.BottomBar.Coupons, Screen.BottomBar.Posts, Screen.BottomBar.Account ) val listAboutApp = listOf( Screen.AboutApp.AccountAndSecurity, Screen.AboutApp.AboutUs, Screen.AboutApp.Help, ) val listAccountAndSecurity = listOf( Screen.AboutApp.AccountInfo, Screen.AboutApp.LoginAndSecurity, Screen.AboutApp.UpdatePassword, ) val listDontUseApp = listOf( Screen.AboutApp.Logout ) val listGift = listOf( Screen.AboutApp.InviteFriend, Screen.AboutApp.Gift )
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Screen/Screen.kt
1050365306
package com.example.shopevoucherapp.presentation import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.material3.Icon import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.compose.currentBackStackEntryAsState import com.example.shopevoucherapp.R import com.example.shopevoucherapp.presentation.Component.TopAppBarView import com.example.shopevoucherapp.presentation.Screen.Screen import com.example.shopevoucherapp.presentation.Screen.listModal import com.example.shopevoucherapp.presentation.navigation.NavigationGraph import com.exyte.animatednavbar.AnimatedNavigationBar import com.exyte.animatednavbar.animation.balltrajectory.Parabolic import com.exyte.animatednavbar.animation.indendshape.shapeCornerRadius import com.exyte.animatednavbar.utils.noRippleClickable @RequiresApi(Build.VERSION_CODES.O) @Composable fun MainScreen ( navController: NavHostController, mainViewModel: MainViewModel = hiltViewModel() ){ val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route val selectedIndex = remember { mutableStateOf(0) } for(i in listModal.indices){ if(listModal[i].route == currentRoute){ selectedIndex.value = i } } var showTopBarAndBottomBar by rememberSaveable { mutableStateOf(true) } showTopBarAndBottomBar = when(currentRoute){ Screen.BottomBar.Home.route -> true Screen.BottomBar.Coupons.route -> true Screen.BottomBar.Posts.route -> true Screen.BottomBar.Account.route -> true else -> false } Scaffold ( topBar = { if(showTopBarAndBottomBar){ TopAppBarView(type = "main", navController = navController) } }, bottomBar = { if(showTopBarAndBottomBar){ AnimatedNavigationBar( selectedIndex = selectedIndex.value, modifier = Modifier.height(55.dp), cornerRadius = shapeCornerRadius(cornerRadius = 34.dp), ballAnimation = Parabolic(tween(300)), ballColor = colorResource(id = R.color.black), barColor = colorResource(id = R.color.schedule_primary), ) { listModal.forEach{item -> Box( modifier = Modifier .fillMaxSize() .noRippleClickable { selectedIndex.value = listModal.indexOf(item) navController.navigateSingleTopTo(item.route) }, contentAlignment = Alignment.Center ){ Icon( painter = painterResource(id = item.icon), contentDescription = item.title, modifier = Modifier.size(20.dp), tint = if(selectedIndex.value == listModal.indexOf(item)) Color.White else Color.Black ) } } } } } ) { NavigationGraph(navController = navController, pd = it) } } fun NavHostController.navigateSingleTopTo(route: String) = this.navigate(route) { launchSingleTop = true restoreState = true [email protected]?.let { popUpTo( it ){ saveState = true } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/MainScreen.kt
1383827268
package com.example.shopevoucherapp.presentation.Authentication.UpdatePassword import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.colorResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavHostController import com.example.shopevoucherapp.R @Composable fun TypeNewPasswordScreen(navHostController: NavHostController){ Column ( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ){ Text( text = "Vui lòng kiểm tra email của bạn để lấy lại mật khẩu! ( Lưu ý : Email gửi đến có thể nằm trong thu rác )", textAlign = TextAlign.Center, style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), fontSize = 20.sp, color = colorResource(id = R.color.question_title) ), modifier = Modifier.padding(10.dp) ) } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Authentication/UpdatePassword/TypeNewpasswordScreen.kt
299754074
package com.example.shopevoucherapp.presentation.Authentication.UpdatePassword import android.util.Log import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import com.example.shopevoucherapp.common.TextFieldState import com.example.shopevoucherapp.data.remote.request.RequestForgotPassword import com.example.shopevoucherapp.domain.use_case.ForgotPasswordUseCase import com.example.shopevoucherapp.util.Resources import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class ForgotPasswordViewModel @Inject constructor( private val forgotPasswordUseCase: ForgotPasswordUseCase ) : ViewModel(){ private val _loadingState = mutableStateOf(false) val loadingState : State<Boolean> = _loadingState private val _emailState = mutableStateOf(TextFieldState()) val emailState : State<TextFieldState> = _emailState fun emailChanged(newEmail : String){ _emailState.value = emailState.value.copy( text = newEmail, error = "" ) } fun isValidEmail(email: String): Boolean { val emailRegex = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+".toRegex() return email.matches(emailRegex) } suspend fun forgotPassword(onNavigation : () -> Unit){ _loadingState.value = true var count = 0 if(emailState.value.text.isEmpty()){ _emailState.value = emailState.value.copy( text = "", error = "Vui lòng nhập đầy đủ thông tin email!" ) } else{ if(isValidEmail(emailState.value.text)){ count++; } else{ _emailState.value =emailState.value.copy( error = "Nhập đúng định dạng email!" ) } } if(count == 1){ when(val res = forgotPasswordUseCase(RequestForgotPassword( emailState.value.text))){ is Resources.Success -> { Log.d("fotgotPassword", res.data.toString()) onNavigation() } is Resources.Error -> { Log.d("fotgotPassword", "Error ${res.errors}") } else ->{ } } } else{ _loadingState.value = false } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Authentication/UpdatePassword/ForgotPasswordViewModel.kt
3845246976
package com.example.shopevoucherapp.presentation.Authentication.UpdatePassword import android.util.Log import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedTextField import androidx.compose.material.Text import androidx.compose.material3.Button import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavHostController import com.example.shopevoucherapp.R import com.example.shopevoucherapp.presentation.Component.LoadingBtnCustom.LoadingButton import com.example.shopevoucherapp.presentation.Component.TopAppBarView import com.example.shopevoucherapp.presentation.Screen.Screen import com.example.shopevoucherapp.presentation.navigateSingleTopTo import kotlinx.coroutines.launch @Composable fun ForgotPasswordScreen( navHostController: NavHostController, forgotPasswordViewModel: ForgotPasswordViewModel = hiltViewModel() ){ val email = forgotPasswordViewModel.emailState.value val focusManager = LocalFocusManager.current val scope = rememberCoroutineScope() val loadingState = forgotPasswordViewModel.loadingState Scaffold ( topBar = { TopAppBarView(type = "Forgot Password", navController = navHostController ) } ) { Column( modifier = Modifier .padding(it) .padding(30.dp) .fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ){ Text( text = "Forgot Password".uppercase(), style = TextStyle(fontSize = 30.sp, fontWeight = FontWeight.ExtraBold) ) Spacer(modifier = Modifier.height(80.dp)) OutlinedTextField( value = email.text, onValueChange = { forgotPasswordViewModel.emailChanged(it) }, placeholder = { Text(text = "Enter the email") }, modifier = Modifier.fillMaxWidth(), isError = email.error != "", keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() Log.d("hideKeyBoard","keyborad") scope.launch { forgotPasswordViewModel.forgotPassword( onNavigation = { navHostController.navigateSingleTopTo(Screen.FunScreen.TypeNewPassword.route) } ) } }), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done, keyboardType = KeyboardType.Email), ) if (email.error != "") { Text( text = email.error ?: "", style = MaterialTheme.typography.body2, color = MaterialTheme.colors.error, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } else { Text( text = "Nhập đúng định dạng email: [email protected]", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), color = Color.LightGray, fontSize = 10.sp ), textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } Spacer(modifier = Modifier.height(20.dp)) LoadingButton( onClick = { scope.launch { forgotPasswordViewModel.forgotPassword( onNavigation = { navHostController.navigateSingleTopTo(Screen.FunScreen.TypeNewPassword.route) } ) } }, loading = loadingState.value, modifier = Modifier .fillMaxWidth() ){ Text( text = "Tiếp tục", modifier = Modifier .padding(10.dp) ) } } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Authentication/UpdatePassword/ForgotPasswordScreen.kt
764218437
package com.example.shopevoucherapp.presentation.Authentication.SignIn import android.util.Log import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import com.example.shopevoucherapp.common.TextFieldState import com.example.shopevoucherapp.data.remote.request.RequestLogin import com.example.shopevoucherapp.data.remote.request.RequestRegister import com.example.shopevoucherapp.domain.use_case.RegisterUseCase import com.example.shopevoucherapp.util.Resources import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.delay import javax.inject.Inject @HiltViewModel class RegisterViewModel @Inject constructor( private val registerUseCase: RegisterUseCase ) : ViewModel() { private val _loadingState = mutableStateOf(false) val loadingState : State<Boolean> = _loadingState private val _emailState = mutableStateOf(TextFieldState()) val emailState : State<TextFieldState> = _emailState private val _passwordState = mutableStateOf(TextFieldState()) val passwordState : State<TextFieldState> = _passwordState private val _rePasswordState = mutableStateOf(TextFieldState()) val rePasswordState : State<TextFieldState> = _rePasswordState private val _stateSus = mutableStateOf("") val stateSus : State<String> = _stateSus fun userNameChanged(newUserName : String){ _emailState.value = emailState.value.copy( text = newUserName, error = "" ) } fun passwordChanged(newPassword : String) { _passwordState.value = passwordState.value.copy( text = newPassword, error = "" ) } fun rePasswordChanged(newPassword : String) { _rePasswordState.value = rePasswordState.value.copy( text = newPassword, error = "" ) } fun isValidEmail(email: String): Boolean { val emailRegex = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+".toRegex() return email.matches(emailRegex) } fun isValidPassword(password: String): Boolean { if (password.length < 8) return false if (password.filter { it.isDigit() }.firstOrNull() == null) return false if (password.filter { it.isLetter() }.filter { it.isUpperCase() }.firstOrNull() == null) return false if (password.filter { it.isLetter() }.filter { it.isLowerCase() }.firstOrNull() == null) return false if (password.filter { !it.isLetterOrDigit() }.firstOrNull() == null) return false return true } suspend fun register(onNavigate : () -> Unit){ var count = 0 _loadingState.value = true if(emailState.value.text.isEmpty()){ _emailState.value = emailState.value.copy( text = "", error = "Vui lòng nhập đầy đủ thông tin email!" ) } else{ if(isValidEmail(emailState.value.text)){ count++; } else{ _emailState.value =emailState.value.copy( error = "Nhập đúng định dạng email!" ) } } if(passwordState.value.text.isEmpty()){ _passwordState.value = passwordState.value.copy( text = "", error = "Vui lòng nhập mật khẩu!" ) } else{ if(isValidPassword(passwordState.value.text)){ count++; } else{ _passwordState.value = passwordState.value.copy( error = "Nhập đúng định dạng mật khẩu!" ) } } if(rePasswordState.value.text.isEmpty()){ _rePasswordState.value = rePasswordState.value.copy( text = "", error = "Vui lòng nhập lại mật khẩu!" ) } else{ if(passwordState.value.text == rePasswordState.value.text){ count++; } else{ _rePasswordState.value = rePasswordState.value.copy( error = "Mật khẩu không trùng khớp!" ) } } if(count == 3){ when(val res = registerUseCase(RequestRegister(emailState.value.text, passwordState.value.text))){ is Resources.Success -> { val user = res.data.user _loadingState.value = false _stateSus.value = "Đăng Kí Thành Công!" delay(2000) onNavigate() } is Resources.Error -> { _loadingState.value = false _passwordState.value = passwordState.value.copy( text = "", error = "Vui lòng kiếm tra lại mật khẩu hoặc tài khoản!" ) } is Resources.Loading ->{ Log.d("Login", "Đang Loading") } } } else{ _loadingState.value = false } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Authentication/SignIn/RegisterViewModel.kt
2464801302
package com.example.shopevoucherapp.presentation.Authentication.SignIn import android.util.Log import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedTextField import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asComposePath import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.graphics.shapes.CornerRounding import androidx.graphics.shapes.Morph import androidx.graphics.shapes.RoundedPolygon import androidx.graphics.shapes.toPath import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.example.shopevoucherapp.R import com.example.shopevoucherapp.presentation.Component.LoadingBtnCustom.LoadingButton import com.example.shopevoucherapp.presentation.Screen.Screen import kotlinx.coroutines.delay import kotlinx.coroutines.launch @Composable fun RegisterScreen( navController: NavController, registerViewModel: RegisterViewModel = hiltViewModel() ){ val focusManager = LocalFocusManager.current val scope = rememberCoroutineScope() val loadingState = registerViewModel.loadingState val infiniteAnimation = rememberInfiniteTransition(label = "infinite animation") val morphProgress = infiniteAnimation.animateFloat( initialValue = 0f, targetValue = 1f, animationSpec = infiniteRepeatable( tween(500), repeatMode = RepeatMode.Reverse ), label = "morph" ) val email = registerViewModel.emailState.value val password = registerViewModel.passwordState.value val stateSus = registerViewModel.stateSus.value val rePassword = registerViewModel.rePasswordState.value var passwordVisible by remember { mutableStateOf(false) } val scaffoldState = rememberScaffoldState() Scaffold( scaffoldState = scaffoldState ) { Column( modifier = Modifier .padding(it) .fillMaxSize() .padding(start = 32.dp, end = 32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = stringResource(id = R.string.login).uppercase(), style = TextStyle(fontSize = 35.sp, fontWeight = FontWeight.ExtraBold) ) Spacer(modifier = Modifier.height(10.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Box(modifier = Modifier .drawWithCache { val triangle = RoundedPolygon( numVertices = 3, radius = size.minDimension / 2f, centerX = size.width / 2f, centerY = size.height / 2f, rounding = CornerRounding( size.minDimension / 10f, smoothing = 0.1f ) ) val square = RoundedPolygon( numVertices = 4, radius = size.minDimension / 2f, centerX = size.width / 2f, centerY = size.height / 2f ) val morph = Morph(start = triangle, end = square) val morphPath = morph .toPath(progress = morphProgress.value) .asComposePath() onDrawBehind { drawPath(morphPath, color = Color.Black) } } .padding(2.dp) ) { IconButton(onClick = { /*TODO*/ }) { Icon( painter = painterResource(id = R.drawable.google), contentDescription = "google", modifier = Modifier.size(20.dp), tint = Color.White ) } } Box( modifier = Modifier .background(Color.Black) .clip(RoundedCornerShape(20.dp)) ) { IconButton(onClick = { /*TODO*/ }) { Icon( painter = painterResource(id = R.drawable.facebook), contentDescription = "facebook", modifier = Modifier.size(20.dp), tint = Color.White ) } } } Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = email.text, onValueChange = { registerViewModel.userNameChanged(it) }, placeholder = { Text(text = "Enter the email") }, modifier = Modifier.fillMaxWidth(), isError = email.error != "", keyboardActions = KeyboardActions(onDone = { focusManager.moveFocus(FocusDirection.Next) }), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done, keyboardType = KeyboardType.Email), ) if (email.error != "") { Text( text = email.error ?: "", style = MaterialTheme.typography.body2, color = MaterialTheme.colors.error, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } else { Text( text = "Nhập đúng định dạng email: [email protected]", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), color = Color.LightGray, fontSize = 10.sp ), textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } Spacer(modifier = Modifier.height(15.dp)) OutlinedTextField( value = password.text, onValueChange = { registerViewModel.passwordChanged(it) }, placeholder = { Text(text = "Enter the password") }, trailingIcon = { IconButton(onClick = { passwordVisible = !passwordVisible }) { Icon( painter = painterResource(id = R.drawable.eye_regular), contentDescription = null, modifier = Modifier.size(15.dp) ) } }, modifier = Modifier.fillMaxWidth(), isError = password.error != "", visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(), keyboardActions = KeyboardActions(onDone = { focusManager.moveFocus(FocusDirection.Next) }), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done, keyboardType = KeyboardType.Email), ) if (password.error != "") { Text( text = password.error ?: "", style = MaterialTheme.typography.body2, color = MaterialTheme.colors.error, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } else { Text( text = "Mật khẩu gồm 8 kí tự trở lên, viết hoa chữ cái đầu, có kí tự đặc biệt.", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), color = Color.LightGray, fontSize = 10.sp ), textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } Spacer(modifier = Modifier.height(15.dp)) OutlinedTextField( value = rePassword.text, onValueChange = { registerViewModel.rePasswordChanged(it) }, placeholder = { Text(text = "ReEnter the password") }, modifier = Modifier.fillMaxWidth(), isError = rePassword.error != "", trailingIcon = { IconButton(onClick = { passwordVisible = !passwordVisible }) { Icon( painter = painterResource(id = R.drawable.eye_regular), contentDescription = null, modifier = Modifier.size(15.dp) ) } }, visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(), keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() Log.d("hideKeyBoard","keyborad") scope.launch { registerViewModel.register(onNavigate = { navController.navigate(Screen.FunScreen.Login.route) }) } }), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done, keyboardType = KeyboardType.Password), ) if (rePassword.error != "") { Text( text = rePassword.error ?: "", style = MaterialTheme.typography.body2, color = MaterialTheme.colors.error, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } else { Text( text = "Nhập lại mật khẩu trùng khớp với mật khẩu đã nhập.", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), color = Color.LightGray, fontSize = 10.sp ), textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } Row( modifier = Modifier .fillMaxWidth() .padding(top = 10.dp, bottom = 10.dp), horizontalArrangement = Arrangement.End ) { Text( text = "Quên mật khẩu ?", ) } Text( text = stateSus, style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), color = colorResource(id = R.color.color_susscess) ) ) LoadingButton( onClick = { scope.launch { registerViewModel.register(onNavigate = { navController.navigate(Screen.FunScreen.Login.route) }) } }, loading = loadingState.value ) { Text(text = stringResource(id = R.string.login)) } Row(modifier = Modifier.padding(10.dp)) { Text(text = "Bạn đã có tài khoản ?") Text( text = " Đăng nhập ngay", style = TextStyle(color = Color.Blue), modifier = Modifier.clickable { navController.navigate(Screen.FunScreen.Login.route) } ) } } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Authentication/SignIn/RegisterScreen.kt
3584886642
package com.example.shopevoucherapp.presentation.Authentication.Login import android.util.Log import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.shopevoucherapp.common.TextFieldState import com.example.shopevoucherapp.data.remote.request.RequestLogin import com.example.shopevoucherapp.data.remote.response.UserResponse.User import com.example.shopevoucherapp.domain.use_case.LoginUseCase import com.example.shopevoucherapp.util.Resources import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val loginUseCase: LoginUseCase, ): ViewModel() { private val _loadingState = mutableStateOf(false) val loadingState : State<Boolean> = _loadingState private val _emailState = mutableStateOf(TextFieldState()) val emailState : State<TextFieldState> = _emailState private val _passwordState = mutableStateOf(TextFieldState()) val passwordState : State<TextFieldState> = _passwordState private val _userInfo = MutableLiveData(User()) val userInf : LiveData<User> = _userInfo fun emailChanged(newEmail : String){ _emailState.value = emailState.value.copy( text = newEmail, error = "" ) } fun passwordChanged(newPassword : String){ _passwordState.value = passwordState.value.copy( text = newPassword, error = "" ) } fun isValidEmail(email: String): Boolean { val emailRegex = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+".toRegex() return email.matches(emailRegex) } fun isValidPassword(password: String): Boolean { if (password.length < 8) return false if (password.filter { it.isDigit() }.firstOrNull() == null) return false if (password.filter { it.isLetter() }.filter { it.isUpperCase() }.firstOrNull() == null) return false if (password.filter { it.isLetter() }.filter { it.isLowerCase() }.firstOrNull() == null) return false if (password.filter { !it.isLetterOrDigit() }.firstOrNull() == null) return false return true } suspend fun login(onNavigate : () -> Unit){ _loadingState.value = true var count = 0 if(emailState.value.text.isEmpty()){ _emailState.value = emailState.value.copy( text = "", error = "Vui lòng nhập đầy đủ thông tin email!" ) } else{ if(isValidEmail(emailState.value.text)){ count++; } else{ _emailState.value =emailState.value.copy( error = "Nhập đúng định dạng email!" ) } } if(passwordState.value.text.isEmpty()){ _passwordState.value = passwordState.value.copy( text = "", error = "Vui lòng nhập mật khẩu!" ) } else{ if(isValidPassword(passwordState.value.text)){ count++; } else{ _passwordState.value = passwordState.value.copy( error = "Nhập đúng định dạng mật khẩu!" ) } } if(count == 2){ when(val res = loginUseCase(RequestLogin(emailState.value.text, passwordState.value.text))){ is Resources.Success -> { val user = res.data.user _loadingState.value = false if (user != null) { _userInfo.value = user } onNavigate() // Log.d("userInfLogin", res.data.toUser()!!.toString()) Log.d("userInfAccount2", userInf.value.toString()) } is Resources.Error -> { _loadingState.value = false _passwordState.value = passwordState.value.copy( text = "", error = "Vui lòng kiếm tra lại mật khẩu hoặc tài khoản!" ) Log.d("userInfAccount2", userInf.value.toString()) } is Resources.Loading ->{ Log.d("Login", "Đang Loading") } } }else{ _loadingState.value = false } } }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Authentication/Login/LoginViewModel.kt
3038867691
package com.example.shopevoucherapp.presentation.Authentication.Login import android.util.Log import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedTextField import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.drawWithCache import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.asComposePath import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.graphics.shapes.CornerRounding import androidx.graphics.shapes.Morph import androidx.graphics.shapes.RoundedPolygon import androidx.graphics.shapes.toPath import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.compose.rememberNavController import com.example.shopevoucherapp.R import com.example.shopevoucherapp.presentation.Component.LoadingBtnCustom.LoadingButton import com.example.shopevoucherapp.presentation.Screen.Screen import com.example.shopevoucherapp.presentation.navigateSingleTopTo import kotlinx.coroutines.launch @Composable fun LoginScreen( navHostController: NavHostController, loginViewModel: LoginViewModel = hiltViewModel() ){ val loadingState = loginViewModel.loadingState val scope = rememberCoroutineScope() val user = loginViewModel.userInf Log.d("StartApp", user.toString()) Log.d("StartApp", "Login") val infiniteAnimation = rememberInfiniteTransition(label = "infinite animation") val morphProgress = infiniteAnimation.animateFloat( initialValue = 0f, targetValue = 1f, animationSpec = infiniteRepeatable( tween(500), repeatMode = RepeatMode.Reverse ), label = "morph" ) val email = loginViewModel.emailState.value val password = loginViewModel.passwordState.value var passwordVisible by remember { mutableStateOf(false) } val focusManager = LocalFocusManager.current val scaffoldState = rememberScaffoldState() Scaffold( scaffoldState = scaffoldState ) { Column( modifier = Modifier .padding(it) .fillMaxSize() .padding(start = 32.dp, end = 32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = stringResource(id = R.string.login).uppercase(), style = TextStyle(fontSize = 35.sp, fontWeight = FontWeight.ExtraBold) ) Spacer(modifier = Modifier.height(10.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Box(modifier = Modifier .drawWithCache { val triangle = RoundedPolygon( numVertices = 3, radius = size.minDimension / 2f, centerX = size.width / 2f, centerY = size.height / 2f, rounding = CornerRounding( size.minDimension / 10f, smoothing = 0.1f ) ) val square = RoundedPolygon( numVertices = 4, radius = size.minDimension / 2f, centerX = size.width / 2f, centerY = size.height / 2f ) val morph = Morph(start = triangle, end = square) val morphPath = morph .toPath(progress = morphProgress.value) .asComposePath() onDrawBehind { drawPath(morphPath, color = Color.Black) } } .padding(2.dp) ) { IconButton(onClick = { /*TODO*/ }) { Icon( painter = painterResource(id = R.drawable.google), contentDescription = "google", modifier = Modifier.size(20.dp), tint = Color.White ) } } Box( modifier = Modifier .background(Color.Black) .clip(RoundedCornerShape(20.dp)) ) { IconButton(onClick = { /*TODO*/ }) { Icon( painter = painterResource(id = R.drawable.facebook), contentDescription = "facebook", modifier = Modifier.size(20.dp), tint = Color.White ) } } } Spacer(modifier = Modifier.height(20.dp)) OutlinedTextField( value = email.text, onValueChange = { loginViewModel.emailChanged(it) }, placeholder = { Text(text = "Enter the email") }, modifier = Modifier.fillMaxWidth(), isError = email.error != "", keyboardActions = KeyboardActions( onDone = { focusManager.moveFocus(FocusDirection.Next) } ), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done, keyboardType = KeyboardType.Email), ) if (email.error != "") { Text( text = email.error ?: "", style = MaterialTheme.typography.body2, color = MaterialTheme.colors.error, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } else { Text( text = "Nhập đúng định dạng email: [email protected]", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), color = Color.LightGray, fontSize = 10.sp ), textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } Spacer(modifier = Modifier.height(15.dp)) OutlinedTextField( value = password.text, onValueChange = { loginViewModel.passwordChanged(it) }, placeholder = { Text(text = "Enter the password") }, modifier = Modifier.fillMaxWidth(), isError = password.error != "", trailingIcon = { IconButton(onClick = { passwordVisible = !passwordVisible }) { Icon( painter = painterResource(id = R.drawable.eye_regular), contentDescription = null, modifier = Modifier.size(15.dp) ) } }, visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(), keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() scope.launch { loginViewModel.login(onNavigate = { navHostController.navigate(Screen.BottomBar.Home.route) }) } }), keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done, keyboardType = KeyboardType.Password), ) if (password.error != "") { Text( text = password.error ?: "", style = MaterialTheme.typography.body2, color = MaterialTheme.colors.error, textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } else { Text( text = "Mật khẩu gồm 8 kí tự trở lên, viết hoa chữ cái đầu, có kí tự đặc biệt.", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), color = Color.LightGray, fontSize = 10.sp ), textAlign = TextAlign.End, modifier = Modifier .fillMaxWidth() .padding(top = 5.dp) ) } Row( modifier = Modifier .fillMaxWidth() .padding(top = 10.dp, bottom = 10.dp), horizontalArrangement = Arrangement.End ) { Text( text = "Quên mật khẩu ?", style = TextStyle( fontFamily = FontFamily(Font(R.font.poppins_medium)), color = colorResource(id = R.color.question_title) ), modifier = Modifier .clickable { navHostController.navigateSingleTopTo(Screen.FunScreen.ForgotPassword.route) } ) } LoadingButton( onClick = { scope.launch { loginViewModel.login(onNavigate = { navHostController.navigate(Screen.BottomBar.Home.route) }) } }, loading = loadingState.value, ){ Text(text = stringResource(id = R.string.login)) } Row(modifier = Modifier.padding(10.dp)) { Text(text = "Bạn chưa có tài khoản ?") Text( text = " Đăng kí ngay", style = TextStyle(color = Color.Blue), modifier = Modifier.clickable { navHostController.navigate(Screen.FunScreen.Register.route) } ) } } } } @Preview(showBackground = true) @Composable fun sdfsd(){ LoginScreen(navHostController = rememberNavController(), viewModel()) }
ShopeVoucherApp/app/src/main/java/com/example/shopevoucherapp/presentation/Authentication/Login/LoginScreen.kt
1141686615
package com.getir.patika.foodcouriers 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.getir.patika.foodcouriers", appContext.packageName) } }
Getir-Android-Kotlin-Bootcamp-w2-v2-Assignment/app/src/androidTest/java/com/getir/patika/foodcouriers/ExampleInstrumentedTest.kt
1487576776
package com.getir.patika.foodcouriers 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) } }
Getir-Android-Kotlin-Bootcamp-w2-v2-Assignment/app/src/test/java/com/getir/patika/foodcouriers/ExampleUnitTest.kt
477887113
package com.getir.patika.foodcouriers import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator class MainActivity : AppCompatActivity() { private lateinit var tabLayout: TabLayout private lateinit var viewPager2: ViewPager2 private lateinit var pagerAdapter: PagerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_account) tabLayout = findViewById(R.id.tab_account) viewPager2 = findViewById(R.id.viewpager_account) pagerAdapter = PagerAdapter(supportFragmentManager,lifecycle).apply { addFragment(CreateAccountFragment()) addFragment(LoginAccountFragment()) } viewPager2.adapter = pagerAdapter TabLayoutMediator(tabLayout,viewPager2){ tab, position -> when(position) { 0 -> { tab.text = "Create Account" } 1 -> { tab.text = "Login Account" } } }.attach() } }
Getir-Android-Kotlin-Bootcamp-w2-v2-Assignment/app/src/main/java/com/getir/patika/foodcouriers/MainActivity.kt
2577925877
package com.getir.patika.foodcouriers import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.lifecycle.Lifecycle import androidx.viewpager2.adapter.FragmentStateAdapter class PagerAdapter(fragmentManager: FragmentManager,lifecycle: Lifecycle): FragmentStateAdapter(fragmentManager,lifecycle) { private val fragmentList: ArrayList<Fragment> = ArrayList() fun addFragment(fragment: Fragment) { fragmentList.add(fragment) } override fun getItemCount(): Int = fragmentList.size override fun createFragment(position: Int): Fragment = fragmentList[position] }
Getir-Android-Kotlin-Bootcamp-w2-v2-Assignment/app/src/main/java/com/getir/patika/foodcouriers/PagerAdapter.kt
3334012323
package com.getir.patika.foodcouriers import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [LoginAccountFragment.newInstance] factory method to * create an instance of this fragment. */ class LoginAccountFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_login_account, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment LoginAccountFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = LoginAccountFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Getir-Android-Kotlin-Bootcamp-w2-v2-Assignment/app/src/main/java/com/getir/patika/foodcouriers/LoginAccountFragment.kt
2356664346
package com.getir.patika.foodcouriers import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [CreateAccountFragment.newInstance] factory method to * create an instance of this fragment. */ class CreateAccountFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_create_account, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment CreateAccountFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = CreateAccountFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Getir-Android-Kotlin-Bootcamp-w2-v2-Assignment/app/src/main/java/com/getir/patika/foodcouriers/CreateAccountFragment.kt
2692917316
package com.example.diceroller 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.diceroller", appContext.packageName) } }
RollerDice/app/src/androidTest/java/com/example/diceroller/ExampleInstrumentedTest.kt
2731144987
package com.example.diceroller 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) } }
RollerDice/app/src/test/java/com/example/diceroller/ExampleUnitTest.kt
1412805653
package com.example.diceroller import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.ImageView import android.widget.TextView import kotlin.random.Random class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val button = findViewById<Button>(R.id.button) button.setOnClickListener { rolldice() } } private fun rolldice() { val textview = findViewById<TextView>(R.id.textView) val image = findViewById<ImageView>(R.id.imageView) val randomnumber = Random.nextInt(6)+1 if (randomnumber ==1){ image.setImageResource(R.drawable.one) } if (randomnumber ==2){ image.setImageResource(R.drawable.two) } if (randomnumber ==3){ image.setImageResource(R.drawable.three) } if (randomnumber ==4){ image.setImageResource(R.drawable.four) } if (randomnumber ==5){ image.setImageResource(R.drawable.five) } if (randomnumber ==6){ image.setImageResource(R.drawable.six) } textview.text = randomnumber.toString() } }
RollerDice/app/src/main/java/com/example/diceroller/MainActivity.kt
3680682381
package com.maps 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.maps", appContext.packageName) } }
Map-Design/app/src/androidTest/java/com/maps/ExampleInstrumentedTest.kt
150834634
package com.maps 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) } }
Map-Design/app/src/test/java/com/maps/ExampleUnitTest.kt
2179301795
package com.maps.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)
Map-Design/app/src/main/java/com/maps/ui/theme/Color.kt
2721273708
package com.maps.ui.theme import android.app.Activity import android.os.Build 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 MapTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { 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 ) }
Map-Design/app/src/main/java/com/maps/ui/theme/Theme.kt
3649180905
package com.maps.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 ) */ )
Map-Design/app/src/main/java/com/maps/ui/theme/Type.kt
3544952013
package com.maps.home import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Canvas import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Person import androidx.compose.material.icons.filled.Phone import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.rounded.Done import androidx.compose.material.icons.rounded.Send import androidx.compose.material.icons.rounded.ShoppingCart import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Divider import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.SheetState import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import com.maps.R import ir.kaaveh.sdpcompose.sdp import ir.kaaveh.sdpcompose.ssp @OptIn(ExperimentalMaterial3Api::class) @Composable fun HomeMap() { val sheetState = rememberModalBottomSheetState() val showBottomSheet by remember { mutableStateOf(false) } val stroke = Stroke( width = 2f, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f) ) Box( modifier = Modifier.fillMaxSize() ) { Image( modifier = Modifier.fillMaxSize(), painter = painterResource(id = R.drawable.map), contentDescription = "image map", contentScale = ContentScale.FillBounds ) if (showBottomSheet.not()) { ShowBottomSheet(sheetState, showBottomSheet, stroke) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ShowBottomSheet(sheetState: SheetState, showBottomSheet: Boolean, stroke: Stroke) { ModalBottomSheet( onDismissRequest = { showBottomSheet.not() }, sheetState = sheetState, containerColor = Color.White ) { Row { Row( modifier = Modifier .weight(1f), verticalAlignment = Alignment.CenterVertically ) { Image( painter = painterResource(id = R.drawable.palestine), contentDescription = "image palestine", modifier = Modifier .padding(start = 5.sdp, top = 0.sdp, end = 3.sdp, bottom = 0.sdp) .wrapContentSize(Alignment.TopCenter) ) Column( modifier = Modifier.padding(3.sdp) ) { Text( text = "Palestine freedom", fontSize = 13.ssp, fontWeight = FontWeight.Bold, color = Color.Black ) Text( text = "#01556044", fontSize = 11.ssp, color = Color.Gray ) } } Row( modifier = Modifier .padding(3.sdp) .weight(1f), horizontalArrangement = Arrangement.End ) { Column( modifier = Modifier.padding(3.sdp) ) { Text( modifier = Modifier.padding(3.sdp), text = "2", fontSize = 15.ssp, color = Color.Red, fontWeight = FontWeight.Bold ) Row { Text( modifier = Modifier.padding(3.sdp), text = "Freedom Code", fontSize = 10.ssp, color = Color.Gray ) Icon( modifier = Modifier .padding(3.sdp) .rotate(180f), painter = painterResource(id = R.drawable.exclamation), contentDescription = "image exclamation", tint = Color.Blue, ) } } } } LineAfterSection() Row( modifier = Modifier .fillMaxWidth() .padding(5.sdp), verticalAlignment = Alignment.CenterVertically ) { Image( Icons.Rounded.Send, contentDescription = "image sent", colorFilter = ColorFilter.tint(Color.Red), modifier = Modifier .background(color = Color.White) .weight(1f) ) Canvas( modifier = Modifier .height(3.sdp) .weight(1f) .padding(1.sdp) ) { drawRoundRect(color = Color.Red, style = stroke) } Image( Icons.Rounded.ShoppingCart, contentDescription = "image shopping", colorFilter = ColorFilter.tint(Color.Red), modifier = Modifier .background(color = Color.White) .weight(1f) ) Canvas( modifier = Modifier .height(3.sdp) .weight(1f) .padding(1.sdp) ) { drawRoundRect(color = Color.Red, style = stroke) } Image( Icons.Rounded.ShoppingCart, contentDescription = "image shopping", colorFilter = ColorFilter.tint(Color.Red), modifier = Modifier .background(color = Color.White) .weight(1f) ) Canvas( modifier = Modifier .height(3.sdp) .weight(2f) .padding(1.sdp) ) { drawRoundRect(color = Color.Gray, style = stroke) } Image( Icons.Rounded.Done, contentDescription = "image Done", colorFilter = ColorFilter.tint(Color.Gray), modifier = Modifier .background(color = Color.White) .weight(1f) ) } LineAfterSection() Row( modifier = Modifier.padding( start = 5.sdp, top = 3.sdp, end = 3.sdp, bottom = 5.sdp ) ) { Row( modifier = Modifier .padding(3.sdp) .weight(2f), ) { Column( modifier = Modifier.padding(3.sdp) ) { Text( text = "Palestine on the way to freedom", fontSize = 10.ssp, color = Color.Gray ) Row( modifier = Modifier.padding(3.sdp) ) { Text( text = "Your order. ETA", fontSize = 10.ssp, color = Color.Gray ) Text( text = " 9:41 PM", fontSize = 10.ssp, color = Color.Black ) } } } Row( modifier = Modifier .padding(3.sdp) .weight(1f), horizontalArrangement = Arrangement.End ) { Box( contentAlignment = Alignment.Center ) { CircularProgressIndicator( progress = 0.5f, color = Color(0xffa1c6c0) ) Text( text = "5:20", fontSize = 10.ssp, color = Color.Black, textAlign = TextAlign.Center ) } } } LineAfterSection() Row( modifier = Modifier.padding(3.sdp) ) { Row( modifier = Modifier .padding(3.sdp) .weight(1f) ) { Text( modifier = Modifier.padding( start = 5.sdp, top = 0.sdp, end = 0.sdp, bottom = 0.sdp ), text = "2 x Items", fontSize = 10.ssp, color = Color.Gray ) Icon( modifier = Modifier .padding(start = 3.sdp, top = 0.sdp, end = 0.sdp, bottom = 0.sdp) .rotate(180f), painter = painterResource(id = R.drawable.exclamation), contentDescription = "image exclamation", tint = Color.Blue, ) } Row( modifier = Modifier .padding(3.sdp) .weight(1f), horizontalArrangement = Arrangement.End ) { Icon( modifier = Modifier .padding(start = 0.sdp, top = 0.sdp, end = 3.sdp, bottom = 0.sdp) .rotate(180f), painter = painterResource(id = R.drawable.exclamation), contentDescription = "image exclamation", ) Text( text = "20.00", fontSize = 10.ssp, color = Color.Black ) } } Spacer( modifier = Modifier.padding( start = 0.sdp, top = 5.sdp, end = 0.sdp, bottom = 0.sdp ) ) Card( modifier = Modifier .fillMaxWidth() .background(Color.White), colors = CardDefaults.cardColors(containerColor = Color.White), elevation = CardDefaults.cardElevation(30.sdp), border = BorderStroke(3.sdp, Color.White), ) { Row { Row( modifier = Modifier .padding(10.sdp) .weight(1f), verticalAlignment = Alignment.CenterVertically ) { Image( Icons.Default.Person, contentDescription = "image Person", modifier = Modifier .wrapContentSize(Alignment.TopCenter) ) Column( modifier = Modifier.padding(3.sdp) ) { Text( text = "Palestine free", fontSize = 13.ssp, fontWeight = FontWeight.Bold, color = Color.Black ) Row { Image( Icons.Default.Star, contentDescription = "image Star", colorFilter = ColorFilter.tint(color = Color.Yellow) ) Text( text = "2.5", fontSize = 11.ssp, color = Color.Black ) } } } Row( modifier = Modifier .padding(10.sdp) .weight(1f), horizontalArrangement = Arrangement.End ) { Icon( Icons.Default.Phone, contentDescription = "image phone", tint = Color(0xFF253BB6), modifier = Modifier.wrapContentSize(Alignment.CenterEnd) ) } } } } } @Composable private fun LineAfterSection() { Divider( modifier = Modifier .fillMaxWidth() .padding(start = 10.sdp, top = 5.sdp, end = 10.sdp, bottom = 5.sdp), color = Color(0xFFACACAC), thickness = 0.sdp ) }
Map-Design/app/src/main/java/com/maps/home/Home.kt
2747345535
package com.maps import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.compose.rememberNavController import com.maps.navgraph.NavGraphOfPage import com.maps.ui.theme.MapTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NavGraphOfPage(navController = rememberNavController()) } } }
Map-Design/app/src/main/java/com/maps/MainActivity.kt
3511816135
package com.kora.route class RouteScreen { companion object { const val HOME_PAGE = "Home" } }
Map-Design/app/src/main/java/com/maps/route/RouteScreen.kt
593146485
package com.maps.navgraph import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.kora.route.RouteScreen import com.maps.home.HomeMap @Composable fun NavGraphOfPage( navController: NavHostController ) { NavHost(navController = navController, startDestination = RouteScreen.HOME_PAGE) { this.composable(route = RouteScreen.HOME_PAGE) { HomeMap() } } }
Map-Design/app/src/main/java/com/maps/navgraph/NavGraph.kt
1127845363
package com.ahmed_apps.camerax_app 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.ahmed_apps.camerax_app", appContext.packageName) } }
CameraX-App/app/src/androidTest/java/com/ahmed_apps/camerax_app/ExampleInstrumentedTest.kt
389974698
package com.ahmed_apps.camerax_app 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) } }
CameraX-App/app/src/test/java/com/ahmed_apps/camerax_app/ExampleUnitTest.kt
2933112272
package com.ahmed_apps.camerax_app.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)
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/ui/theme/Color.kt
3757314432
package com.ahmed_apps.camerax_app.ui.theme import android.app.Activity import android.graphics.Color import android.os.Build 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 CameraXAppTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { 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 = Color.BLACK WindowCompat.getInsetsController( window, view ).isAppearanceLightStatusBars = false } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/ui/theme/Theme.kt
1168401828
package com.ahmed_apps.camerax_app.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 ) */ )
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/ui/theme/Type.kt
2464015497
package com.ahmed_apps.camerax_app import android.app.Application import dagger.hilt.android.HiltAndroidApp /** * @author Ahmed Guedmioui */ @HiltAndroidApp class App: Application()
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/App.kt
2292493911
package com.ahmed_apps.camerax_app import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.ahmed_apps.camerax_app.presentation.CameraScreen import com.ahmed_apps.camerax_app.ui.theme.CameraXAppTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!arePermissionsGranted()) { ActivityCompat.requestPermissions( this, CAMERA_PERMISSION, 100 ) } setContent { CameraXAppTheme { CameraScreen(this) } } } fun arePermissionsGranted(): Boolean { return CAMERA_PERMISSION.all { perssion -> ContextCompat.checkSelfPermission( applicationContext, perssion ) == PackageManager.PERMISSION_GRANTED } } companion object { val CAMERA_PERMISSION = arrayOf( Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO ) } }
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/MainActivity.kt
3400013745
package com.ahmed_apps.camerax_app.di import com.ahmed_apps.camerax_app.data.repository.CameraRepositoryImpl import com.ahmed_apps.camerax_app.domain.repository.CameraRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton /** * @author Ahmed Guedmioui */ @Module @InstallIn(SingletonComponent::class) abstract class CameraRepositoryModule { @Binds @Singleton abstract fun bindCameraRepository( cameraRepositoryImpl: CameraRepositoryImpl ): CameraRepository }
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/di/CameraRepositoryModule.kt
2405173493
package com.ahmed_apps.camerax_app.data.repository import android.app.Application import android.content.ContentResolver import android.content.ContentValues import android.graphics.Bitmap import android.graphics.Matrix import android.net.Uri import android.os.Build import android.os.Environment import android.provider.MediaStore import androidx.annotation.RequiresApi import androidx.camera.core.ImageCapture import androidx.camera.core.ImageProxy import androidx.camera.video.FileOutputOptions import androidx.camera.video.Recording import androidx.camera.video.VideoRecordEvent import androidx.camera.view.LifecycleCameraController import androidx.camera.view.video.AudioConfig import androidx.core.content.ContextCompat import com.ahmed_apps.camerax_app.R import com.ahmed_apps.camerax_app.domain.repository.CameraRepository import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File import javax.inject.Inject /** * @author Ahmed Guedmioui */ class CameraRepositoryImpl @Inject constructor( private val application: Application ) : CameraRepository { private var recoding: Recording? = null override suspend fun takePhoto( controller: LifecycleCameraController ) { controller.takePicture( ContextCompat.getMainExecutor(application), object : ImageCapture.OnImageCapturedCallback() { override fun onCaptureSuccess(image: ImageProxy) { super.onCaptureSuccess(image) val matrix = Matrix().apply { postRotate( image.imageInfo.rotationDegrees.toFloat() ) } val imageBitmap = Bitmap.createBitmap( image.toBitmap(), 0, 0, image.width, image.height, matrix, true ) CoroutineScope(Dispatchers.IO).launch { savePhoto(imageBitmap) } } } ) } override suspend fun recordVideo( controller: LifecycleCameraController ) { if (recoding != null) { recoding?.stop() recoding = null return } val timeInMillis = System.currentTimeMillis() val file = File( application.filesDir, "${timeInMillis}_video" + ".mp4" ) recoding = controller.startRecording( FileOutputOptions.Builder(file).build(), AudioConfig.create(true), ContextCompat.getMainExecutor(application) ) { event -> if (event is VideoRecordEvent.Finalize) { if (event.hasError()) { recoding?.close() recoding = null } else { CoroutineScope(Dispatchers.IO).launch { saveVideo(file) } } } } } @RequiresApi(Build.VERSION_CODES.Q) private suspend fun savePhoto(bitmap: Bitmap) { withContext(Dispatchers.IO) { val resolver: ContentResolver = application.contentResolver val imageCollection = MediaStore.Images.Media.getContentUri( MediaStore.VOLUME_EXTERNAL_PRIMARY ) val appName = application.getString(R.string.app_name) val timeInMillis = System.currentTimeMillis() val imageContentValues: ContentValues = ContentValues().apply { put( MediaStore.Images.Media.DISPLAY_NAME, "${timeInMillis}_image" + ".jpg" ) put( MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/$appName" ) put(MediaStore.Images.Media.MIME_TYPE, "image/jpg") put(MediaStore.MediaColumns.DATE_TAKEN, timeInMillis) put(MediaStore.MediaColumns.IS_PENDING, 1) } val imageMediaStoreUri: Uri? = resolver.insert( imageCollection, imageContentValues ) imageMediaStoreUri?.let { uri -> try { resolver.openOutputStream(uri)?.let { outputStream -> bitmap.compress( Bitmap.CompressFormat.JPEG, 100, outputStream ) } imageContentValues.clear() imageContentValues.put( MediaStore.MediaColumns.IS_PENDING, 0 ) resolver.update( uri, imageContentValues, null, null ) } catch (e: Exception) { e.printStackTrace() resolver.delete(uri, null, null) } } } } @RequiresApi(Build.VERSION_CODES.Q) private suspend fun saveVideo(file: File) { withContext(Dispatchers.IO) { val resolver: ContentResolver = application.contentResolver val videoCollection = MediaStore.Video.Media.getContentUri( MediaStore.VOLUME_EXTERNAL_PRIMARY ) val appName = application.getString(R.string.app_name) val timeInMillis = System.currentTimeMillis() val videoContentValues: ContentValues = ContentValues().apply { put( MediaStore.Video.Media.DISPLAY_NAME, file.name ) put( MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/$appName" ) put(MediaStore.Video.Media.MIME_TYPE, "video/mp4") put(MediaStore.MediaColumns.DATE_ADDED, timeInMillis / 1000) put(MediaStore.MediaColumns.DATE_MODIFIED, timeInMillis / 1000) put(MediaStore.MediaColumns.DATE_TAKEN, timeInMillis) put(MediaStore.Video.Media.IS_PENDING, 1) } val videoMediaStoreUri: Uri? = resolver.insert( videoCollection, videoContentValues ) videoMediaStoreUri?.let { uri -> try { resolver.openOutputStream(uri)?.use { outputStream -> resolver.openInputStream( Uri.fromFile(file) )?.use { inputStream -> inputStream.copyTo(outputStream) } } videoContentValues.clear() videoContentValues.put(MediaStore.MediaColumns.IS_PENDING, 0) resolver.update( uri, videoContentValues, null, null ) } catch (e: Exception) { e.printStackTrace() resolver.delete(uri, null, null) } } } } }
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/data/repository/CameraRepositoryImpl.kt
3895333770
package com.ahmed_apps.camerax_app.domain.repository import androidx.camera.view.LifecycleCameraController /** * @author Ahmed Guedmioui */ interface CameraRepository { suspend fun takePhoto( controller: LifecycleCameraController ) suspend fun recordVideo( controller: LifecycleCameraController ) }
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/domain/repository/CameraRepository.kt
3243000626
package com.ahmed_apps.camerax_app.presentation import android.app.Activity import android.content.Intent import android.net.Uri import androidx.camera.core.CameraSelector import androidx.camera.view.CameraController import androidx.camera.view.LifecycleCameraController import androidx.camera.view.PreviewView import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Camera import androidx.compose.material.icons.filled.Cameraswitch import androidx.compose.material.icons.filled.PhotoLibrary import androidx.compose.material.icons.filled.Stop import androidx.compose.material.icons.filled.Videocam import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import androidx.hilt.navigation.compose.hiltViewModel import com.ahmed_apps.camerax_app.MainActivity import com.ahmed_apps.camerax_app.R /** * @author Ahmed Guedmioui */ @Composable fun CameraScreen( activity: Activity ) { val controller = remember { LifecycleCameraController( activity.applicationContext ).apply { setEnabledUseCases( CameraController.IMAGE_CAPTURE or CameraController.VIDEO_CAPTURE ) } } val cameraViewModel = hiltViewModel<CameraViewModel>() val isRecording by cameraViewModel.isRecording.collectAsState() Box( modifier = Modifier .fillMaxSize() .background(Color.Black) ) { val lifecycleOwner = LocalLifecycleOwner.current AndroidView( modifier = Modifier.fillMaxSize(), factory = { PreviewView(it).apply { this.controller = controller controller.bindToLifecycle(lifecycleOwner) } } ) Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 80.dp) .align(Alignment.BottomCenter), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .clip(RoundedCornerShape(14.dp)) .size(45.dp) .background(MaterialTheme.colorScheme.primary) .clickable { Intent( Intent.ACTION_VIEW, Uri.parse( "content://media/internal/images/media" ) ).also { activity.startActivity(it) } }, contentAlignment = Alignment.Center ) { Icon( imageVector = Icons.Default.PhotoLibrary, contentDescription = stringResource(R.string.open_gallery), tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(26.dp) ) } Spacer(modifier = Modifier.width(1.dp)) Box( modifier = Modifier .clip(CircleShape) .size(60.dp) .background(MaterialTheme.colorScheme.primary) .clickable { if ((activity as MainActivity).arePermissionsGranted()) { cameraViewModel.onRecordVideo(controller) } }, contentAlignment = Alignment.Center ) { Icon( imageVector = if (isRecording) Icons.Default.Stop else Icons.Default.Videocam, contentDescription = stringResource(R.string.record_video), tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(26.dp) ) } Box( modifier = Modifier .clip(CircleShape) .size(60.dp) .background(MaterialTheme.colorScheme.primary) .clickable { if ((activity as MainActivity).arePermissionsGranted()) { cameraViewModel.onTakePhoto(controller) } }, contentAlignment = Alignment.Center ) { Icon( imageVector =Icons.Default.Camera, contentDescription = stringResource(R.string.take_photo), tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(26.dp) ) } Spacer(modifier = Modifier.width(1.dp)) Box( modifier = Modifier .clip(RoundedCornerShape(14.dp)) .size(45.dp) .background(MaterialTheme.colorScheme.primary) .clickable { controller.cameraSelector = if (controller.cameraSelector == CameraSelector.DEFAULT_BACK_CAMERA) { CameraSelector.DEFAULT_FRONT_CAMERA } else { CameraSelector.DEFAULT_BACK_CAMERA } }, contentAlignment = Alignment.Center ) { Icon( imageVector = Icons.Default.Cameraswitch, contentDescription = stringResource(R.string.switch_camera_preview), tint = MaterialTheme.colorScheme.onPrimary, modifier = Modifier.size(26.dp) ) } } } }
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/presentation/CameraScreen.kt
393887108
package com.ahmed_apps.camerax_app.presentation import androidx.camera.view.LifecycleCameraController import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.ahmed_apps.camerax_app.domain.repository.CameraRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject /** * @author Ahmed Guedmioui */ @HiltViewModel class CameraViewModel @Inject constructor( private val cameraRepository: CameraRepository ): ViewModel() { private val _isRecording = MutableStateFlow(false) val isRecording = _isRecording.asStateFlow() fun onTakePhoto( controller: LifecycleCameraController ) { viewModelScope.launch { cameraRepository.takePhoto(controller) } } fun onRecordVideo( controller: LifecycleCameraController ) { _isRecording.update { !isRecording.value } viewModelScope.launch { cameraRepository.recordVideo(controller) } } }
CameraX-App/app/src/main/java/com/ahmed_apps/camerax_app/presentation/CameraViewModel.kt
122835303
package com.example.println_password import android.content.Intent import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.TextView import android.widget.Toast import com.example.println_password.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding private val passwordDigits = mutableListOf<Int?>(null, null, null, null, null, null) private val correctPassword = listOf(1, 2, 3, 4, 5, 6) // Здесь нужно указать правильный пароль override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.tv1.setOnClickListener { setNumber(1, binding.tochka1) } binding.tv2.setOnClickListener { setNumber(2, binding.tochka2) } binding.tv3.setOnClickListener { setNumber(3, binding.tochka3) } binding.tv4.setOnClickListener { setNumber(4, binding.tochka4) } binding.tv5.setOnClickListener { setNumber(5, binding.tochka5) } binding.tv6.setOnClickListener { setNumber(6, binding.tochka6) } binding.btnSubmit.setOnClickListener { checkPassword() } binding.btnClear.setOnClickListener { clearPassword() } } private fun setNumber(number: Int, textView: TextView) { for (i in passwordDigits.indices) { if (passwordDigits[i] == null) { passwordDigits[i] = number break } } val index = number - 1 val textColor = if (passwordDigits[index] != null) Color.YELLOW else Color.GRAY textView.setTextColor(textColor) } private fun checkPassword() { if (passwordDigits == correctPassword) { // Пароль верный Toast.makeText(this, "Пароль верный", Toast.LENGTH_SHORT).show() // Здесь можно выполнить действия, соответствующие правильному паролю } else { // Пароль неверный Toast.makeText(this, "Пароль неверный", Toast.LENGTH_SHORT).show() // Здесь можно выполнить действия, соответствующие неправильному паролю } } private fun clearPassword() { passwordDigits.fill(null) // Очистка массива пароля binding.tochka1.setTextColor(Color.GRAY) binding.tochka2.setTextColor(Color.GRAY) binding.tochka3.setTextColor(Color.GRAY) binding.tochka4.setTextColor(Color.GRAY) binding.tochka5.setTextColor(Color.GRAY) binding.tochka6.setTextColor(Color.GRAY) } }
Println_Password/app/src/main/java/com/example/println_password/MainActivity.kt
3175160643
package com.example.println_password import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" /** * A simple [Fragment] subclass. * Use the [HelloFragment.newInstance] factory method to * create an instance of this fragment. */ class HelloFragment : Fragment() { // TODO: Rename and change types of parameters private var param1: String? = null private var param2: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { param1 = it.getString(ARG_PARAM1) param2 = it.getString(ARG_PARAM2) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_hello, container, false) } companion object { /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment HelloFragment. */ // TODO: Rename and change types and number of parameters @JvmStatic fun newInstance(param1: String, param2: String) = HelloFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } }
Println_Password/app/src/main/java/com/example/println_password/HelloFragment.kt
1624607942
package com.example.emart_app import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
eMart_shop/android/app/src/main/kotlin/com/example/emart_app/MainActivity.kt
316438046
package com.iphoto.plus 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.retrofit_demo", appContext.packageName) } }
retrofit_demo/app/src/androidTest/java/com/iphoto/plus/ExampleInstrumentedTest.kt
140487360
package com.iphoto.plus 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) } }
retrofit_demo/app/src/test/java/com/iphoto/plus/ExampleUnitTest.kt
3593833340
package com.iphoto.plus.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)
retrofit_demo/app/src/main/java/com/iphoto/plus/ui/theme/Color.kt
816437806
package com.iphoto.plus.ui.theme import android.app.Activity import android.os.Build 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 Retrofit_demoTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { 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 ) }
retrofit_demo/app/src/main/java/com/iphoto/plus/ui/theme/Theme.kt
3151771839
package com.iphoto.plus.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 ) */ )
retrofit_demo/app/src/main/java/com/iphoto/plus/ui/theme/Type.kt
2478191078
package com.iphoto.plus.home data class TeacherWeekBean ( private val weekPlanId :String, private val weekName :String, private val gradeId :String, private val teachingId :String, private val startDate :String, private val endDate :String )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/TeacherWeekBean.kt
2904236998
package com.iphoto.plus.home data class LoginResponseBean( val classId: String, val gradeId: String, val headPhoto: String, val phone: String, val schoolId: String, val schoolName: String, val schoolVersion: Int, val teacherId: String, val teacherName: String, val token: String )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/LoginResponseBean.kt
3340501813
package com.iphoto.plus.home data class RegisterBean( val phone: String, val password: String, val username: String, val verifyCode: String )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/RegisterBean.kt
3241945316
package com.iphoto.plus.home data class PhoneBean( val phone: String )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/PhoneBean.kt
2891370731
package com.iphoto.plus.home data class ResponseBean( val code :Int, val message :String , val data : Data ) data class Data( val string: String )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/ResponseBean.kt
3404227504
package com.iphoto.plus.home data class LoginBean( val password: String, val phone: String )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/LoginBean.kt
4040241774
package com.iphoto.plus.home data class User( private var serverTime: String, )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/User.kt
3647750717
package com.iphoto.plus.home data class UserBean( val createdAt: String, val phone: String, val status: Int, val username: String )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/UserBean.kt
276145016
package com.iphoto.plus.home class WeekPlanListBean : ArrayList<WeekPlanListBeanItem>() data class WeekPlanListBeanItem( val endDate: String, val gradeId: String, val id: String, val planName: String, val selected: Boolean, val startDate: String )
retrofit_demo/app/src/main/java/com/iphoto/plus/home/WeekPlanListBean.kt
4294063411
package com.iphoto.plus import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.iphoto.plus.base.MyAppContext import com.iphoto.plus.home.LoginBean import com.iphoto.plus.home.PhoneBean import com.iphoto.plus.home.RegisterBean import com.iphoto.plus.home.WeekPlanListBeanItem import com.iphoto.plus.internet.CoroutineUtil import com.iphoto.plus.internet.HttpRequest import com.iphoto.plus.internet.RetrofitClient import com.iphoto.plus.ui.theme.Retrofit_demoTheme import com.iphoto.plus.utils.SpUtil class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Retrofit_demoTheme { // // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("在成长") Log.i("levi", MyAppContext.context.packageName) // BottomAppBar { // setContent { // val navList = listOf("首页","课程","发现","我的") // } // } } } } } } private fun register(){ val registerBean =RegisterBean("13839131251","666666","Levi","1345") HttpRequest.execute{ it.register(registerBean) // SpUtil.encode("token", login.data.token) } } private fun sendCode(){ val phoneBean =PhoneBean("13839131251") HttpRequest.execute{ it.sendCode(phoneBean) } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { var weekPlanList by remember { mutableStateOf(emptyList<WeekPlanListBeanItem>()) } Column { Text( text = "Hello $name!", modifier = modifier ) Button(onClick = { sendCode() }) { Text(text = "登录") } Button(onClick = { CoroutineUtil.execMain { val gradeId = SpUtil.decodeString("gradeId") val responseList = RetrofitClient.apiService.getWeekPlanList(gradeId.toString()) weekPlanList = responseList.data } }) { Text(text = "请求周计划列表") } PuppyListItem(weekPlanList) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun PuppyListItem(weekPlanList: List<WeekPlanListBeanItem>) { LazyColumn( Modifier.fillMaxHeight(), //设置Padding为20dp contentPadding = PaddingValues(horizontal = 20.dp, vertical = 20.dp), //设置item的间距为10dp verticalArrangement = Arrangement.spacedBy(10.dp) ) { //添加多个item,回调中没有数据的下标 items(weekPlanList.size) { Card(onClick = { Log.i("levi", "点击==>$it") }) { Text("第$it 个Item") } Text(text = "${weekPlanList.get(it).planName}") } } } @Preview(showBackground = true) @Composable fun GreetingPreview() { Retrofit_demoTheme { Greeting("Android") } }
retrofit_demo/app/src/main/java/com/iphoto/plus/MainActivity.kt
2536428968
package com.iphoto.plus.utils import android.content.Context import android.content.SharedPreferences import com.iphoto.plus.base.MyAppContext object PreferenceManager { private const val PREF_NAME = "home_preference" private const val KEY_TOKEN = "token" private fun getSharedPreferences(context: Context): SharedPreferences { return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE) } fun saveToken( token: String) { val editor = getSharedPreferences(MyAppContext.context).edit() editor.putString(KEY_TOKEN, token) editor.apply() } fun getToken(): String? { return getSharedPreferences(MyAppContext.context).getString(KEY_TOKEN, null) } }
retrofit_demo/app/src/main/java/com/iphoto/plus/utils/PreferenceManager.kt
2919847322
package com.iphoto.plus.utils import android.app.Activity import java.lang.ref.WeakReference object ActivityManager { // 弱引用 private var sCurrentActivityWeakRef: WeakReference<Activity>? = null fun getCurrentActivity(): Activity? = sCurrentActivityWeakRef?.get() fun setCurrentActivity(activity: Activity) { sCurrentActivityWeakRef = WeakReference(activity) } }
retrofit_demo/app/src/main/java/com/iphoto/plus/utils/ActivityManager.kt
1239524951
package com.iphoto.plus.utils import android.os.Parcelable import com.tencent.mmkv.MMKV import java.util.Collections object SpUtil { var mmkv: MMKV? = null init { mmkv = MMKV.defaultMMKV() } fun encode(key: String, value: Any?) { when (value) { is String -> mmkv?.encode(key, value) is Float -> mmkv?.encode(key, value) is Boolean -> mmkv?.encode(key, value) is Int -> mmkv?.encode(key, value) is Long -> mmkv?.encode(key, value) is Double -> mmkv?.encode(key, value) is ByteArray -> mmkv?.encode(key, value) else -> return } } fun <T : Parcelable> encode(key: String, t: T?) { if(t ==null){ return } mmkv?.encode(key, t) } fun encode(key: String, sets: Set<String>?) { if(sets ==null){ return } mmkv?.encode(key, sets) } fun decodeInt(key: String): Int? { return mmkv?.decodeInt(key, 0) } fun decodeDouble(key: String): Double? { return mmkv?.decodeDouble(key, 0.00) } fun decodeLong(key: String): Long? { return mmkv?.decodeLong(key, 0L) } fun decodeBoolean(key: String): Boolean? { return mmkv?.decodeBool(key, false) } fun decodeFloat(key: String): Float? { return mmkv?.decodeFloat(key, 0F) } fun decodeByteArray(key: String): ByteArray? { return mmkv?.decodeBytes(key) } fun decodeString(key: String): String? { return mmkv?.decodeString(key, "") } fun <T : Parcelable> decodeParcelable(key: String, tClass: Class<T>): T? { return mmkv?.decodeParcelable(key, tClass) } fun decodeStringSet(key: String): Set<String>? { return mmkv?.decodeStringSet(key, Collections.emptySet()) } fun removeKey(key: String) { mmkv?.removeValueForKey(key) } fun clearAll() { mmkv?.clearAll() } }
retrofit_demo/app/src/main/java/com/iphoto/plus/utils/SpUtil.kt
3674066059
package com.iphoto.plus.utils import android.widget.Toast object ToastUtil { private var toast: Toast? = null fun show( content: String) { if (toast == null) { toast = Toast.makeText(ActivityManager.getCurrentActivity(), content, Toast.LENGTH_SHORT) } else { toast!!.setText(content) } toast!!.show() } }
retrofit_demo/app/src/main/java/com/iphoto/plus/utils/ToastUtil.kt
2040578382
package com.iphoto.plus.utils import android.app.AlertDialog import android.view.View import android.widget.LinearLayout import com.iphoto.plus.R object DialogManager { fun showRound(): AlertDialog? = ActivityManager.getCurrentActivity()?.let { AlertDialog.Builder(it).create().apply { window?.run { // 设置背景透明,去四个角 setLayout( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) // 设置固定宽带,高度自适应 setBackgroundDrawableResource(R.color.color_transparent) } // 设置点击dialog的外部能否取消弹窗 setCanceledOnTouchOutside(false) // 设置能不能返回键取消弹窗 setCancelable(false) show() setContentView( View.inflate(it, R.layout.alert_dialog_round, null).apply { // 设置成顶层视图 bringToFront() } ) } } }
retrofit_demo/app/src/main/java/com/iphoto/plus/utils/DialogManager.kt
718203253
package com.iphoto.plus.internet import android.util.Log import okhttp3.ResponseBody import retrofit2.Converter import java.lang.reflect.Type class GsonResponseBodyConverter<T>( private val type: Type ) : Converter<ResponseBody, T> { override fun convert(value: ResponseBody): T { val response = value.string() val httpResult = JsonUtil.json2Object(response, Response::class.java) // 这里是定义成code 200为正常,不正常则抛出之前定义好的异常,在自定义的协程异常处理类中处理 Log.d("response","response: ${httpResult.message}") return if (httpResult.code == 200) { JsonUtil.json2Object<T>(response, type) } else { throw RequestException(response) } } }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/GsonResponseBodyConverter.kt
3486982862
package com.iphoto.plus.internet fun interface HttpPredicate { suspend fun execute(api: ApiService) }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/HttpPredicate.kt
88975436
package com.iphoto.plus.internet import okhttp3.RequestBody import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.Type object GsonResponseConverterFactory : Converter.Factory() { override fun responseBodyConverter( type: Type, annotations: Array<Annotation?>, retrofit: Retrofit ): Converter<ResponseBody, *> { return GsonResponseBodyConverter<Type>(type) } override fun requestBodyConverter( type: Type, parameterAnnotations: Array<out Annotation>, methodAnnotations: Array<out Annotation>, retrofit: Retrofit ): Converter<*, RequestBody> { return GsonRequestBodyConverter<Type>(type) } }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/GsonResponseConverterFactory.kt
945874378
package com.iphoto.plus.internet import android.util.Log import com.iphoto.plus.utils.SpUtil import okhttp3.Interceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import java.util.concurrent.TimeUnit object RetrofitClient { private const val Authorization = "Auth" private const val UserAgent = "User-Agent" private val okHttpClient: OkHttpClient = OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .addInterceptor { chain: Interceptor.Chain -> // 这里配置了统一拦截器用以添加token 如果不需要可以去掉 val request = chain.request().newBuilder().apply { addHeader(UserAgent, "Android") SpUtil.decodeString("token")?.let { addHeader(Authorization, it) } }.build() Log.d("Request","request: ${request.method()} ${request.url()} ${request.body().toString()}\n${request.headers()}") chain.proceed(request) } .build() private val retrofit: Retrofit = Retrofit.Builder() .baseUrl("http://139.224.53.155:3000") .addConverterFactory(GsonResponseConverterFactory) .client(okHttpClient) .build() val apiService: ApiService = retrofit.create(ApiService::class.java) }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/RetrofitClient.kt
377651766
package com.iphoto.plus.internet import com.iphoto.plus.utils.DialogManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch object HttpRequest { fun execute(http: HttpPredicate) = CoroutineUtil.execMain { val showRound = DialogManager.showRound() try { http.execute(RetrofitClient.apiService) } catch (e: Exception) { throw e } finally { showRound?.let { if (it.isShowing) { it.cancel() } } } } fun executeAsync(http: HttpPredicate) = CoroutineScope(Dispatchers.Main).launch(CoroutineHandler) { http.execute(RetrofitClient.apiService) } }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/HttpRequest.kt
4189287569
package com.iphoto.plus.internet import com.google.gson.Gson import com.google.gson.TypeAdapter import com.google.gson.reflect.TypeToken import okhttp3.MediaType import okhttp3.RequestBody import okio.Buffer import retrofit2.Converter import java.io.OutputStreamWriter import java.io.Writer import java.lang.reflect.Type import java.nio.charset.Charset class GsonRequestBodyConverter<T>( type: Type ) : Converter<T, RequestBody> { private val gson: Gson = JsonUtil.gson private val adapter: TypeAdapter<T> = gson.getAdapter(TypeToken.get(type)) as TypeAdapter<T> override fun convert(value: T): RequestBody? { val buffer = Buffer() val writer: Writer = OutputStreamWriter(buffer.outputStream(), Charset.forName("UTF-8")) val jsonWriter = gson.newJsonWriter(writer) adapter.write(jsonWriter, value) jsonWriter.close() return RequestBody.create( MediaType.get("application/json; charset=UTF-8"), buffer.readByteString() ) } }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/GsonRequestBodyConverter.kt
320100631
package com.iphoto.plus.internet import android.util.Log import com.iphoto.plus.utils.ToastUtil import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.cancel import retrofit2.HttpException import java.net.ConnectException import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext object CoroutineHandler : AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler { override fun handleException(context: CoroutineContext, exception: Throwable) { Log.d("ResponseException","请求异常"+exception.message.toString()) // 处理 when (exception.javaClass.name) { ConnectException::class.java.name -> ToastUtil.show("请求异常,请检查网络") RequestException::class.java.name -> { // 处理服务器错误 val httpResult = JsonUtil.json2Object(exception.message.toString(), Response::class.java) when (httpResult.code) { 1000011 -> ToastUtil.show("请求异常,服务器异常") } } HttpException::class.java.name -> { when (exception.message.toString()) { } } } context.cancel() } }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/CoroutineHandler.kt
102834635
package com.iphoto.plus.internet import java.lang.RuntimeException class RequestException constructor( response:String ): RuntimeException(response)
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/RequestException.kt
1622272833
package com.iphoto.plus.internet data class Response<T> ( val code: Int, val message: String, val data: T )
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/Response.kt
3031637717
package com.iphoto.plus.internet import com.iphoto.plus.home.LoginBean import com.iphoto.plus.home.LoginResponseBean import com.iphoto.plus.home.PhoneBean import com.iphoto.plus.home.RegisterBean import com.iphoto.plus.home.ResponseBean import com.iphoto.plus.home.UserBean import com.iphoto.plus.home.WeekPlanListBean import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Query interface ApiService { /** * 发送验证码 */ @POST("/api/v1/aliyun/sendVerifyCode") suspend fun sendCode(@Body phoneBean: PhoneBean): Response<ResponseBean> /** * 注册 */ @POST("/api/v1/auth/register") suspend fun register(@Body registerBean: RegisterBean): Response<ResponseBean> /** * 登录 */ @POST("/api/v1/auth/login") suspend fun login(@Body loginBean: LoginBean): Response<LoginResponseBean> @GET("/javaApi/weekPlan/getWeekPlanListForSelect") suspend fun getWeekPlanList(@Query ("gradeId")gradeId:String): Response<WeekPlanListBean> @GET("/api/v1/user/info") suspend fun getUserInfo(): Response<UserBean> }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/ApiService.kt
280378118
package com.iphoto.plus.internet import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch object CoroutineUtil { fun interface CoroutinePredicate { suspend fun execute() } fun execMain(code: CoroutinePredicate) = CoroutineScope(Dispatchers.Main).launch(CoroutineHandler) { code.execute() } fun execIO(code: CoroutinePredicate) = CoroutineScope(Dispatchers.IO).launch(CoroutineHandler) { code.execute() } }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/CoroutineUtil.kt
2129986466
package com.iphoto.plus.internet import com.google.gson.Gson import com.google.gson.reflect.TypeToken import java.lang.reflect.Type import java.util.LinkedList object JsonUtil { val gson: Gson = Gson() fun <T> object2Json(obj: T): String = gson.toJson(obj) fun <T> json2Object(json: String, obj: Type): T = gson.fromJson(json, obj) fun <T> json2Object(json: String, obj: Class<T>): T = gson.fromJson(json, obj) fun <T> json2List(json: String): List<T> { return gson.fromJson(json, object : TypeToken<LinkedList<T>>() {}.type) } fun <T> list2Json(list: List<T>): String { return object2Json(list) } }
retrofit_demo/app/src/main/java/com/iphoto/plus/internet/JsonUtil.kt
4199823586
package com.iphoto.plus.base import android.content.Context object MyAppContext { lateinit var context: Context }
retrofit_demo/app/src/main/java/com/iphoto/plus/base/MyAppContext.kt
2288053246
package com.iphoto.plus.base import android.app.Activity import android.app.Application import android.os.Bundle import com.iphoto.plus.utils.ActivityManager import com.tencent.mmkv.MMKV class BaseApplication : Application() { companion object { fun getInstance(): BaseApplication = Inner.instance } private object Inner { lateinit var instance: BaseApplication } override fun onCreate() { super.onCreate() Inner.instance = this MyAppContext.context = this MMKV.initialize(this) // 监听所有Activity的生命周期回调 registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { } override fun onActivityStarted(activity: Activity) { } override fun onActivityResumed(activity: Activity) { // 在此处设置当前的Activity ActivityManager.setCurrentActivity(activity) } override fun onActivityPaused(activity: Activity) { } override fun onActivityStopped(activity: Activity) { } override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) { } override fun onActivityDestroyed(activity: Activity) { } }) } }
retrofit_demo/app/src/main/java/com/iphoto/plus/base/BaseApplication.kt
413416067
package com.example.firstjetpackcomposeproject 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.firstjetpackcomposeproject", appContext.packageName) } }
JetpackComposeBasics/app/src/androidTest/java/com/example/firstjetpackcomposeproject/ExampleInstrumentedTest.kt
3904309528
package com.example.firstjetpackcomposeproject 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) } }
JetpackComposeBasics/app/src/test/java/com/example/firstjetpackcomposeproject/ExampleUnitTest.kt
998533974
package com.example.firstjetpackcomposeproject.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
JetpackComposeBasics/app/src/main/java/com/example/firstjetpackcomposeproject/ui/theme/Shape.kt
3910709475
package com.example.firstjetpackcomposeproject.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
JetpackComposeBasics/app/src/main/java/com/example/firstjetpackcomposeproject/ui/theme/Color.kt
461389493
package com.example.firstjetpackcomposeproject.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun FirstJetPackComposeProjectTheme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
JetpackComposeBasics/app/src/main/java/com/example/firstjetpackcomposeproject/ui/theme/Theme.kt
3694949612
package com.example.firstjetpackcomposeproject.ui.theme import androidx.compose.material.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( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
JetpackComposeBasics/app/src/main/java/com/example/firstjetpackcomposeproject/ui/theme/Type.kt
587108189
package com.example.firstjetpackcomposeproject import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.modifier.modifierLocalConsumer import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.firstjetpackcomposeproject.ui.theme.FirstJetPackComposeProjectTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { FirstJetPackComposeProjectTheme { // Greeting("Android") // var count by remember { // mutableStateOf(0) // } // Column( // modifier = Modifier.fillMaxSize(), // verticalArrangement = Arrangement.Center, // horizontalAlignment = Alignment.CenterHorizontally // ) { // Text( // text = count.toString(), // fontSize = 30.sp // ) // Button(onClick = { // count++ // }) { // Text(text = "click me!") // } // } var name by remember{ mutableStateOf("") } var names by remember{ mutableStateOf(listOf<String>()) } Column ( modifier = Modifier .fillMaxSize() .padding(16.dp) ){ Row( modifier = Modifier.fillMaxWidth() ) { OutlinedTextField( value = name , onValueChange = {text-> name = text }, modifier = Modifier.weight(1f) ) Spacer(modifier = Modifier.width(16.dp)) Button(onClick = { if( name.isNotBlank() ){ names = names + name name = "" } }) { Text( text = "Add" ) } } LazyColumn{ items(names){currentName-> Text( text = currentName, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) Divider() } } } } } } } @Composable fun Greeting(name: String) { LazyColumn( modifier = Modifier.fillMaxSize()){ items(20){ Icon( imageVector = Icons.Default.Add, contentDescription = null, modifier = Modifier.size(120.dp) ) } } } @Preview(showBackground = true) @Composable fun DefaultPreview() { FirstJetPackComposeProjectTheme { Greeting("Android") } }
JetpackComposeBasics/app/src/main/java/com/example/firstjetpackcomposeproject/MainActivity.kt
691873636
package com.example.draganddraw 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.draganddraw", appContext.packageName) } }
DragandDraw/app/src/androidTest/java/com/example/draganddraw/ExampleInstrumentedTest.kt
3931124979
package com.example.draganddraw 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) } }
DragandDraw/app/src/test/java/com/example/draganddraw/ExampleUnitTest.kt
854881090
package com.example.draganddraw import android.animation.AnimatorSet import android.animation.ArgbEvaluator import android.animation.ObjectAnimator import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.view.animation.AccelerateInterpolator import android.view.animation.AnimationSet import androidx.core.content.ContextCompat class MainActivity : AppCompatActivity() { private lateinit var sceneView: View private lateinit var sunView:View private lateinit var SkyView:View private val blueSkyColor:Int by lazy { ContextCompat.getColor(this,R.color.blue_sky) } private val sunsetSkyColor:Int by lazy { ContextCompat.getColor(this,R.color.sunset_sky) } private val nightSkyColor:Int by lazy { ContextCompat.getColor(this,R.color.night_sky) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sceneView=findViewById(R.id.scene) sunView=findViewById(R.id.sun) SkyView=findViewById(R.id.sky) sceneView.setOnClickListener{ startAnimation() } } private fun startAnimation(){ val sunYStart=sunView.top.toFloat() val sunYEnd=SkyView.height.toFloat() val heightAnimator=ObjectAnimator .ofFloat(sunView,"y",sunYStart,sunYEnd) .setDuration(3600) heightAnimator.interpolator=AccelerateInterpolator() val sunsetSkyAnimator=ObjectAnimator .ofInt(SkyView,"backgroundColor",blueSkyColor,sunsetSkyColor) .setDuration(3000) sunsetSkyAnimator.setEvaluator(ArgbEvaluator()) val nightSkyAnimator=ObjectAnimator.ofInt(SkyView,"backgroundColor",sunsetSkyColor,nightSkyColor) .setDuration(1500) nightSkyAnimator.setEvaluator(ArgbEvaluator()) val animationSet= AnimatorSet() animationSet.play(heightAnimator) .with(sunsetSkyAnimator) .before(nightSkyAnimator) animationSet.start() } }
DragandDraw/app/src/main/java/com/example/draganddraw/MainActivity.kt
1933985657
package com.example.draganddraw import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class DragAndDrawActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_drag_and_draw) } }
DragandDraw/app/src/main/java/com/example/draganddraw/DragAndDrawActivity.kt
457408641
package com.example.draganddraw import android.graphics.PointF class Box(val start:PointF) { var end:PointF=start val left:Float get() = Math.min(start.x,end.x) val right:Float get() = Math.max(start.x,end.x) val top:Float get() = Math.min(start.y,end.y) val bottom:Float get()=Math.max(start.y,end.y) }
DragandDraw/app/src/main/java/com/example/draganddraw/Box.kt
2342765361
package com.example.draganddraw import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.Point import android.graphics.PointF import android.util.AttributeSet import android.util.Log import android.view.MotionEvent import android.view.View private const val TAG="BoxDrawingView" class BoxDrawingView(context: Context,attrs:AttributeSet?=null): View(context,attrs) { override fun onDraw(canvas: Canvas) { canvas.drawPaint(backgroundPaint) boxen.forEach { box -> canvas.drawRect(box.left,box.top,box.right,box.bottom,boxPaint) } } private var currentBox:Box?=null private val boxen= mutableListOf<Box>() private val boxPaint= Paint().apply { color=0x22ff0000.toInt() } private val backgroundPaint=Paint().apply { color=0xfff8efe0.toInt() } override fun onTouchEvent(event: MotionEvent): Boolean { val current=PointF(event.x,event.y) var action="" when(event.action){ MotionEvent.ACTION_DOWN->{ action="Action_DOWN" currentBox=Box(current).also { boxen.add(it) } } MotionEvent.ACTION_MOVE->{ action="Action_MOVE" updateCurrentBox(current) } MotionEvent.ACTION_UP->{ action="Action_UP" updateCurrentBox(current) currentBox=null } MotionEvent.ACTION_CANCEL->{ action="Action_CANCEL" currentBox=null } } Log.i(TAG,"$action at x=${current.x},y=${current.y}") return true } private fun updateCurrentBox(current:PointF){ currentBox?.let { it.end=current invalidate() } } }
DragandDraw/app/src/main/java/com/example/draganddraw/BoxDrawingView.kt
87488205