path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
GymForce/app/src/androidTest/java/com/example/gymforce/ExampleInstrumentedTest.kt | 249399386 | package com.example.gymforce
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.gymforce", appContext.packageName)
}
} |
GymForce/app/src/test/java/com/example/gymforce/ExampleUnitTest.kt | 481696382 | package com.example.gymforce
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)
}
} |
GymForce/app/src/main/java/com/example/gymforce/ui/theme/Color.kt | 3839003479 | package com.example.gymforce.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)
val orange = Color(0xFFF34336) |
GymForce/app/src/main/java/com/example/gymforce/ui/theme/Theme.kt | 1122311933 | package com.example.gymforce.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 GymForceTheme(
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
)
} |
GymForce/app/src/main/java/com/example/gymforce/ui/theme/Type.kt | 985565317 | package com.example.gymforce.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
)
*/
) |
GymForce/app/src/main/java/com/example/gymforce/navigation/BottomNavItem.kt | 3882552941 | package com.example.gymforce.navigation
import com.example.gymforce.R
sealed class BottomNavItem(var title:String, var icon:Int, var screen_route:String) {
data object Setting : BottomNavItem("Setting", R.drawable.setting, "setting")
data object Exercises : BottomNavItem("Exercises", R.drawable.img_2, "exercises")
data object Tools : BottomNavItem("Tools", R.drawable.img_1, "tools")
} |
GymForce/app/src/main/java/com/example/gymforce/navigation/BottomNavigation.kt | 2880913657 | package com.example.gymforce.navigation
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.example.gymforce.R
@Composable
fun MyBottomNavigation(navController: NavController) {
val items = listOf(
BottomNavItem.Setting,
BottomNavItem.Exercises,
BottomNavItem.Tools
)
BottomNavigation(
backgroundColor = colorResource(id = R.color.orange),
contentColor = Color.Black, modifier = Modifier.height(55.dp),
) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
items.forEach { item ->
BottomNavigationItem(
icon = {
Icon(
painterResource(id = item.icon),
modifier = Modifier
.padding(top = 6.dp)
.size(25.dp),
contentDescription = item.title
)
},
label = {
Text(
text = item.title,
fontSize = 12.sp
)
},
selectedContentColor = Color.Black,
unselectedContentColor = Color.White.copy(0.7f),
alwaysShowLabel = true,
selected = currentRoute == item.screen_route,
onClick = {
navController.navigate(item.screen_route) {
navController.graph.startDestinationRoute?.let { screen_route ->
popUpTo(screen_route) {
saveState = true
}
}
launchSingleTop = true
restoreState = true
}
}
)
}
}
} |
GymForce/app/src/main/java/com/example/gymforce/navigation/NavigationGraph.kt | 1212457380 | package com.example.gymforce.navigation
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.gymforce.screens.Exercises.ExercisesScreen
import com.example.gymforce.screens.setting.SettingScreen
import com.example.gymforce.screens.tools.ToolsScreen
import com.example.gymforce.screens.type.TypeScreen
@Composable
fun NavigationGraph(navController: NavHostController) {
NavHost(
navController = navController,
startDestination = BottomNavItem.Exercises.screen_route
) {
composable(BottomNavItem.Setting.screen_route) {
SettingScreen()
}
composable(BottomNavItem.Exercises.screen_route) {
ExercisesScreen(navController)
}
composable(BottomNavItem.Tools.screen_route) {
ToolsScreen(navController)
}
composable("type training screen"){
TypeScreen(navController)
}
}
} |
GymForce/app/src/main/java/com/example/gymforce/models/TrainingCardItem.kt | 1198705512 | package com.example.gymforce.models
import com.example.gymforce.R
sealed class TrainingCardItem(
var numOfDay: String,
var workOutName: String,
var workOutImage: Int
) {
data object ChestDay : TrainingCardItem("Day 1", "Chest", R.drawable.icon_app)
data object BackDay : TrainingCardItem("Day 2", "Back", R.drawable.icon_app)
data object ShoulderDay : TrainingCardItem("Day 3", "Shoulder", R.drawable.icon_app)
data object ArmsDay : TrainingCardItem("Day 4", "Arms", R.drawable.icon_app)
data object LegDay : TrainingCardItem("Day 5", "Leg", R.drawable.icon_app)
data object Off : TrainingCardItem("Day 6", "Off", R.drawable.icon_app)
} |
GymForce/app/src/main/java/com/example/gymforce/models/TrainingTypeItem.kt | 3683506393 | package com.example.gymforce.models
class TrainingTypeItem
(
) {
} |
GymForce/app/src/main/java/com/example/gymforce/screens/splash/ui/theme/Color.kt | 3965027970 | package com.example.gymforce.screens.splash.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) |
GymForce/app/src/main/java/com/example/gymforce/screens/splash/ui/theme/Theme.kt | 2179957717 | package com.example.gymforce.screens.splash.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 GymForceTheme(
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
)
} |
GymForce/app/src/main/java/com/example/gymforce/screens/splash/ui/theme/Type.kt | 2106438172 | package com.example.gymforce.screens.splash.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
)
*/
) |
GymForce/app/src/main/java/com/example/gymforce/screens/splash/SplashContent.kt | 3813851426 | package com.example.gymforce.screens.splash
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import com.example.gymforce.R
@Composable
fun SplashContent() {
Column(
modifier = Modifier
.fillMaxSize()
.background(color = colorResource(id = R.color.orange))
.paint(
painterResource(id = R.drawable.icon_app),
)
) {
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/splash/SplashActivity.kt | 2346088553 | package com.example.gymforce.screens.splash
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.example.gymforce.screens.MainActivity
import com.example.gymforce.screens.splash.ui.theme.GymForceTheme
class SplashActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GymForceTheme {
// A surface container using the 'background' color from the theme
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this@SplashActivity, MainActivity::class.java)
startActivity(intent)
finish()
},2500)
SplashContent()
}
}
}
}
|
GymForce/app/src/main/java/com/example/gymforce/screens/tools/ToolsScreen.kt | 2831859166 | package com.example.gymforce.screens.tools
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
@Composable
fun ToolsScreen(navHostController: NavHostController) {
ToolsContent(navHostController)
} |
GymForce/app/src/main/java/com/example/gymforce/screens/tools/ToolsContent.kt | 3272780063 | package com.example.gymforce.screens.tools
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
@Composable
fun ToolsContent(navHostController: NavHostController) {
Column(modifier = Modifier.fillMaxSize(),Arrangement.Center) {
Text(text = "Tools Screen")
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/MainActivity.kt | 2226121826 | package com.example.gymforce.screens
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.ui.Modifier
import androidx.navigation.compose.rememberNavController
import com.example.gymforce.ui.theme.GymForceTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
MainScreenView(navController)
}
}
}
|
GymForce/app/src/main/java/com/example/gymforce/screens/type/TypeScreenTopBar.kt | 3585904976 | package com.example.gymforce.screens.type
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
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 com.example.gymforce.R
@Composable
fun TypeScreenTopBar(trainingScreenName: String) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Image(
painter = painterResource(id = R.drawable.icon_back),
contentDescription = "icon back",
modifier = Modifier.padding(end = 120.dp, top = 10.dp)
)
Text(
text = trainingScreenName,
color = Color.Black,
fontFamily = FontFamily.Default,
fontSize = 28.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(end = 150.dp, top = 10.dp)
.align(
Alignment.CenterVertically
)
)
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/type/TypeScreen.kt | 3085556269 | package com.example.gymforce.screens.type
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
@Composable
fun TypeScreen(navHostController: NavHostController) {
TypeScreenContent(navHostController = navHostController)
} |
GymForce/app/src/main/java/com/example/gymforce/screens/type/TypeScreenContent.kt | 3038866041 | package com.example.gymforce.screens.type
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import com.example.gymforce.models.TrainingCardItem
@Composable
fun TypeScreenContent(navHostController: NavHostController) {
Column(
modifier = Modifier.fillMaxSize(),
Arrangement.Top,
Alignment.CenterHorizontally)
{
TypeScreenTopBar(trainingScreenName = TrainingCardItem.ChestDay.workOutName)
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/TrainingCard.kt | 2817614677 | package com.example.gymforce.screens.Exercises
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
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.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.example.gymforce.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TrainingCard(name: String, day: String, image: Int, navController: NavHostController) {
Card(
modifier = Modifier
.fillMaxWidth()
.height(115.dp)
.padding(8.dp),
colors = CardDefaults.cardColors(
containerColor = Color.Gray.copy(0.9f)
),
shape = RoundedCornerShape(10.dp),
elevation = CardDefaults.cardElevation(
defaultElevation = 7.dp
),
onClick = {
navController.navigate("type training screen")
}
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(8.dp)
) {
Image(
painter = painterResource(id = image),
contentDescription = "",
modifier = Modifier
.size(90.dp)
.padding(end = 8.dp, top = 2.dp)
.align(Alignment.CenterVertically)
)
Column (modifier= Modifier.fillMaxWidth(.7f).padding(start = 8.dp)){
Text(text = day, fontSize = 22.sp, fontWeight = FontWeight.Bold)
Text(text = name, fontSize = 22.sp, fontWeight = FontWeight.Normal)
}
Icon(
painter = painterResource(id = R.drawable.icon_arrow),
contentDescription = "icon go to training Screen ",
modifier = Modifier.weight(0.2f)
)
}
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/ExercisesTopBar.kt | 2391339692 | package com.example.gymforce.screens.Exercises
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
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
@Composable
fun ExercisesTopBar() {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Text(
text = "Exercises",
color = Color.Black,
fontFamily = FontFamily.Default,
fontSize = 28.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(10.dp)
.align(
Alignment.CenterVertically
)
)
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/ExercisesLazyColumn.kt | 2895789151 | package com.example.gymforce.screens.Exercises
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.example.gymforce.models.TrainingCardItem
@Composable
fun ExercisesLazyColumn(navHostController: NavHostController) {
val list = listOf(
TrainingCardItem.ChestDay,
TrainingCardItem.BackDay,
TrainingCardItem.ShoulderDay,
TrainingCardItem.ArmsDay,
TrainingCardItem.LegDay,
TrainingCardItem.Off,
)
LazyColumn (
modifier = Modifier
.fillMaxSize()
.padding(bottom = 55.dp)
) {
item {
list.forEach { item ->
TrainingCard(
name = item.workOutName,
day = item.numOfDay,
image = item.workOutImage,
navHostController
)
}
}
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/ExercisesContent.kt | 8893835 | package com.example.gymforce.screens.Exercises
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
@Composable
fun ExercisesContent(navHostController: NavHostController) {
Column(
modifier = Modifier.fillMaxSize(),
Arrangement.Top,
Alignment.CenterHorizontally
)
{
ExercisesTopBar()
ExercisesLazyColumn(navHostController)
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/Exercises/ExercisesScreen.kt | 3280228017 | package com.example.gymforce.screens.Exercises
import androidx.compose.runtime.Composable
import androidx.navigation.NavHostController
@Composable
fun ExercisesScreen(navHostController: NavHostController) {
ExercisesContent(navHostController)
} |
GymForce/app/src/main/java/com/example/gymforce/screens/setting/SettingScreen.kt | 3903746527 | package com.example.gymforce.screens.setting
import androidx.compose.runtime.Composable
@Composable
fun SettingScreen() {
SettingContent()
} |
GymForce/app/src/main/java/com/example/gymforce/screens/setting/SettingContent.kt | 3012612995 | package com.example.gymforce.screens.setting
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun SettingContent() {
Column(modifier = Modifier.fillMaxSize(),Arrangement.Center) {
Text(text = "Setting Screen")
}
} |
GymForce/app/src/main/java/com/example/gymforce/screens/MainScreen.kt | 3255350445 | package com.example.gymforce.screens
import android.annotation.SuppressLint
import androidx.compose.material.Scaffold
import androidx.compose.runtime.Composable
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.example.gymforce.navigation.MyBottomNavigation
import com.example.gymforce.navigation.NavigationGraph
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun MainScreenView(navController: NavHostController) {
Scaffold(
bottomBar = { MyBottomNavigation(navController = navController) }
) {
NavigationGraph(navController = navController)
}
} |
Musicify-Frontend/android/app/src/main/java/com/musicify/MainActivity.kt | 2262849672 | package com.musicify
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "Musicify"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
|
Musicify-Frontend/android/app/src/main/java/com/musicify/MainApplication.kt | 1746667819 | package com.musicify
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}
}
|
Legend_2048_Game/app/src/androidTest/java/uz/boxodir/test2048game/ExampleInstrumentedTest.kt | 2072309904 | package uz.boxodir.test2048game
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.test2048game", appContext.packageName)
}
} |
Legend_2048_Game/app/src/test/java/uz/boxodir/test2048game/ExampleUnitTest.kt | 1391882498 | package uz.boxodir.test2048game
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)
}
} |
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/settings/Settings.kt | 2878834548 | package uz.boxodir.test2048game.settings
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
class Settings constructor(context: Context) {
fun savePos(txt: String) {
editor.putString("CURRENT_MATRIX", txt).apply()
}
fun saveLastMatrix(txt: String) {
editor.putString("LAST", txt).apply()
}
fun saveState(boolean: Boolean) {
editor.putBoolean("STATE", boolean).apply()
}
fun isPlaying() = pref.getBoolean("STATE", false)
fun getItems(): String? {
return pref.getString("CURRENT_MATRIX", "")
}
fun lastItems(): String? {
return pref.getString("LAST", "")
}
fun saveScore(score: Int) {
editor.putInt("SCORE", score).apply()
}
fun saveLastScore(lastScore: Int) {
editor.putInt("LAST_SCORE", lastScore).apply()
}
fun saveRecord(record: Int) {
editor.putInt("RECORD", record).apply()
}
fun getScore(): Int = pref.getInt("SCORE", 0)
fun getScoreLast(): Int = pref.getInt("LAST_SCORE", 0)
fun getRecord(): Int = pref.getInt("RECORD", 0)
private var pref: SharedPreferences = context.getSharedPreferences("2048", Context.MODE_PRIVATE)
private var editor: SharedPreferences.Editor = pref.edit()
companion object {
@SuppressLint("StaticFieldLeak")
private lateinit var instance: Settings
fun init(context: Context) {
if (!(Companion::instance.isInitialized)) {
instance = Settings(context)
}
}
fun getInstance(): Settings {
return instance
}
}
} |
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/repository/AppRepository.kt | 335284080 | package uz.boxodir.test2048game.repository
import android.annotation.SuppressLint
import android.content.Context
import android.util.Log
import android.widget.Toast
import uz.boxodir.test2048game.settings.Settings
import kotlin.random.Random
class AppRepository private constructor() {
var level = 0
private var lastLevel = 0
private var record = 0
companion object {
@SuppressLint("StaticFieldLeak")
private lateinit var settings: Settings
@SuppressLint("StaticFieldLeak")
private var instance: AppRepository? = null
@SuppressLint("StaticFieldLeak")
private lateinit var context: Context
fun init(context: Context) {
Companion.context = context
settings = Settings.getInstance()
}
fun getInstance(): AppRepository {
if (instance == null)
instance = AppRepository()
return instance!!
}
}
init {
record = settings.getRecord()
}
fun getRecord() = record
private val NEW_ELEMENT = 2
val matrix = arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0)
)
val lastMatrix = arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0)
)
init {
if (settings.isPlaying()) {
Log.d("OOO", "Load Data")
loadData()
} else {
addFirst()
addFirst()
}
}
fun backOldState() {
/*for (i in lastMatrix.indices) {
for (j in lastMatrix.indices) {
matrix[i][j] = lastMatrix[i][j]
Log.d("OOO", "${lastMatrix[i][j]}")
}
}*/
swap(matrix, lastMatrix)
/*swap(lastMatrix, lastMatrix2)
swap(lastMatrix2, lastMatrix3)*/
level = lastLevel
/*lastLevel = lastLevel2
lastLevel2 = lastLevel3*/
}
fun addFirst() {
val emptyList = ArrayList<Pair<Int, Int>>()
for (i in matrix.indices) {
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) {
emptyList.add(Pair(i, j))
}
}
}
val randomPos = Random.nextInt(0, emptyList.size)
matrix[emptyList[randomPos].first][emptyList[randomPos].second] = NEW_ELEMENT
lastMatrix[emptyList[randomPos].first][emptyList[randomPos].second] = NEW_ELEMENT
}
private fun addNewElement() {
val emptyList = ArrayList<Pair<Int, Int>>()
for (i in matrix.indices) {
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) {
emptyList.add(Pair(i, j))
}
}
}
Log.d("KKK", "${isClickable()}")
if (emptyList.isEmpty() && !isClickable()) {
Toast.makeText(context, "Game over", Toast.LENGTH_SHORT).show()
clear()
} else {
val randomPos = Random.nextInt(0, emptyList.size)
matrix[emptyList[randomPos].first][emptyList[randomPos].second] = NEW_ELEMENT
}
}
fun moveToLeft() {
val temp = matrix.copyData()
lastLevel = level
swap(lastMatrix, matrix)
for (i in matrix.indices) {
val amounts = ArrayList<Int>(4)
var bool = true
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) continue
if (amounts.isEmpty()) amounts.add(matrix[i][j])
else {
if (amounts.last() == matrix[i][j] && bool) {
level += amounts.last()
record = if (record < level) level else record
amounts[amounts.size - 1] = amounts.last() * 2
bool = false
} else {
amounts.add(matrix[i][j])
bool = true
}
}
matrix[i][j] = 0
}
for (k in amounts.indices) {
matrix[i][k] = amounts[k]
}
}
if (!temp.contentDeepEquals(matrix))
addNewElement()
}
fun moveToRight() {
val temp = matrix.copyData()
lastLevel = level
swap(lastMatrix, matrix)
for (i in matrix.indices) {
val amounts = ArrayList<Int>(4)
var bool = true
for (j in matrix[i].size - 1 downTo 0) {
if (matrix[i][j] == 0) continue
if (amounts.isEmpty()) amounts.add(matrix[i][j])
else {
if (amounts.last() == matrix[i][j] && bool) {
level += amounts.last()
record = if (record < level) level else record
amounts[amounts.size - 1] = amounts.last() * 2
bool = false
} else {
amounts.add(matrix[i][j])
bool = true
}
}
matrix[i][j] = 0
}
for (k in amounts.indices) {
matrix[i][matrix[i].size - k - 1] = amounts[k]
}
}
if (!temp.contentDeepEquals(matrix))
addNewElement()
}
fun moveUp() {
val temp = matrix.copyData()
lastLevel = level
swap(lastMatrix, matrix)
for (i in matrix.indices) {
val amount = ArrayList<Int>()
var bool = true
for (j in matrix[i].indices) {
if (matrix[j][i] == 0) continue
if (amount.isEmpty()) amount.add(matrix[j][i])
else {
if (amount.last() == matrix[j][i] && bool) {
level += amount.last()
record = if (record < level) level else record
amount[amount.size - 1] = amount.last() * 2
bool = false
} else {
bool = true
amount.add(matrix[j][i])
}
}
matrix[j][i] = 0
}
for (j in 0 until amount.size) {
matrix[j][i] = amount[j]
}
}
if (!temp.contentDeepEquals(matrix))
addNewElement()
}
fun moveDown() {
val temp = matrix.copyData()
lastLevel = level
swap(lastMatrix, matrix)
for (i in matrix.indices) {
val amount = ArrayList<Int>()
var bool = true
for (j in matrix[i].size - 1 downTo 0) {
if (matrix[j][i] == 0) continue
if (amount.isEmpty()) amount.add(matrix[j][i])
else {
if (amount.last() == matrix[j][i] && bool) {
level += amount.last()
record = if (record < level) level else record
amount[amount.size - 1] = amount.last() * 2
bool = false
} else {
bool = true
amount.add(matrix[j][i])
}
}
matrix[j][i] = 0
}
for (k in amount.size - 1 downTo 0) {
matrix[3 - k][i] = amount[k]
}
}
if (!temp.contentDeepEquals(matrix))
addNewElement()
}
fun clear() {
for (i in matrix.indices) {
for (j in matrix[i].indices) {
matrix[i][j] = 0
}
}
level = 0
lastLevel = 0
swap(lastMatrix, matrix)
settings.saveState(false)
addFirst()
addFirst()
}
fun saveItems() {
val sb: StringBuilder = StringBuilder()
val sbLast: StringBuilder = StringBuilder()
for (i in matrix.indices) {
for (j in matrix[i].indices) {
sb.append(matrix[i][j].toString())
sbLast.append(lastMatrix[i][j])
sb.append("##")
sbLast.append("##")
}
}
settings.savePos(sb.toString())
settings.saveLastMatrix(sbLast.toString())
settings.saveScore(level)
settings.saveLastScore(lastLevel)
settings.saveState(true)
}
fun saveRecord(int: Int) {
settings.saveRecord(int)
}
fun loadData() {
level = settings.getScore()
lastLevel = settings.getScoreLast()
record = settings.getRecord()
val txt = settings.getItems()?.split("##")!!
val txtLast = settings.lastItems()?.split("##")!!
Log.d("YYY", txtLast.toString())
for (i in 0 until txt.size - 1) {
Log.d("PPP", "$i")
matrix[i / 4][i % 4] = txt[i].toInt()
if (!txtLast.isEmpty()) {
lastMatrix[i / 4][i % 4] = txtLast[i].toInt()
}
}
}
fun swap(a: Array<Array<Int>>, b: Array<Array<Int>>) {
for (i in b.indices) {
for (j in b[i].indices) {
a[i][j] = b[i][j]
}
}
}
fun setState(boolean: Boolean) {
settings.saveState(boolean)
}
fun isPlaying() = settings.isPlaying()
fun isClickable(): Boolean {
for (i in matrix.indices) {
val emptyList = ArrayList<Int>(4)
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) {
return true
}
if (emptyList.isEmpty()) {
emptyList.add(matrix[i][j])
} else {
if (emptyList.last() == matrix[i][j]) {
return true
} else {
emptyList.add(matrix[i][j])
}
}
}
}
for (i in matrix[0].indices) {
val emptyList = ArrayList<Int>(4)
for (j in matrix.indices) {
if (matrix[j][i] == 0) {
return true
}
if (emptyList.isEmpty()) {
emptyList.add(matrix[j][i])
} else {
if (emptyList.last() == matrix[j][i])
return true
else
emptyList.add(matrix[j][i])
}
}
}
return false
}
fun restart() {
clear()
instance = null
}
}
fun Array<Array<Int>>.copyData() = map { it.clone() }.toTypedArray()
|
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/app/App.kt | 2507280380 | package uz.boxodir.test2048game.app
import android.app.Application
import uz.boxodir.test2048game.repository.AppRepository
import uz.boxodir.test2048game.settings.Settings
class App:Application() {
override fun onCreate() {
Settings.init(this)
AppRepository.init(this)
super.onCreate()
}
} |
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/utils/BackgroundUtil.kt | 2352654098 | package uz.boxodir.test2048game.utils
import uz.boxodir.test2048game.R
class BackgroundUtil {
private val backgroundMap = HashMap<Int, Int>()
private val backgroundText = HashMap<Int, Int>()
init {
loadMap()
}
private fun loadMap() {
backgroundMap[0] = R.drawable.bg_item_0
backgroundMap[2] = R.drawable.bg_item_2
backgroundMap[4] = R.drawable.bg_item_4
backgroundMap[8] = R.drawable.bg_item_8
backgroundMap[16] = R.drawable.bg_item_16
backgroundMap[32] = R.drawable.bg_item_32
backgroundMap[64] = R.drawable.bg_item_64
backgroundMap[128] = R.drawable.bg_item_128
backgroundMap[256] = R.drawable.bg_item_256
backgroundMap[512] = R.drawable.bg_item_512
backgroundMap[1024] = R.drawable.bg_item_1024
backgroundMap[2048] = R.drawable.bg_item_2048
backgroundMap[4096] = R.drawable.bg_corner4096
backgroundMap[8192] = R.drawable.bg_corner8192
backgroundMap[16384] = R.drawable.bg_corner16384
backgroundText[0] = R.color.white
backgroundText[8] = R.color.white
backgroundText[16] = R.color.white
backgroundText[32] = R.color.white
backgroundText[64] = R.color.white
backgroundText[128] = R.color.white
backgroundText[256] = R.color.white
backgroundText[512] = R.color.white
backgroundText[1024] = R.color.white
backgroundText[2048] = R.color.white
backgroundText[4096] = R.color.white
backgroundText[8192] = R.color.white
backgroundText[16384] = R.color.white
backgroundText[0] = R.color.white
// backgroundText[2] = R.color.qoraroq
// backgroundText[4] = R.color.qoraroq
}
fun colorByCount(amount: Int): Int {
return backgroundMap.getOrDefault(amount, R.drawable.empty_corner)
}
fun textColorByCount(i: Int): Int {
return backgroundText.getOrDefault(i, R.color.white)
}
} |
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/utils/MyTouchListener.kt | 3650243439 | package uz.boxodir.test2048game.utils
import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import uz.boxodir.test2048game.model.SideEnum
import kotlin.math.abs
class MyTouchListener(context:Context) : View.OnTouchListener {
private val myGestureDetector = GestureDetector(context, MyGestureListener())
private var myMovementSideListener : ((SideEnum) -> Unit)?= null
override fun onTouch(v: View, event: MotionEvent): Boolean {
myGestureDetector.onTouchEvent(event)
return true
}
inner class MyGestureListener: GestureDetector.SimpleOnGestureListener() {
override fun onFling(
e1: MotionEvent?,
e2: MotionEvent,
velocityX: Float,
velocityY: Float
): Boolean {
if (abs(e2.x - e1!!.x)> 100 || abs(e2.y - e1.y) > 100){
if (abs(e2.x - e1.x) < abs(e2.y - e1.y)){
if (e2.y > e1.y){
myMovementSideListener?.invoke(SideEnum.DOWN)
}else{
myMovementSideListener?.invoke(SideEnum.UP)
}
}
else{
if (e2.x > e1.x){
myMovementSideListener?.invoke(SideEnum.RIGHT)
}else{
myMovementSideListener?.invoke(SideEnum.LEFT)
}
}
}
return super.onFling(e1, e2, velocityX, velocityY)
}
}
fun setMyMovementSideListener(block:(SideEnum) -> Unit){
myMovementSideListener = block
}
} |
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/screen/MainActivity.kt | 2632653780 | package uz.boxodir.test2048game.screen
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import uz.boxodir.test2048game.R
class MainActivity : AppCompatActivity() {
private lateinit var playgame: AppCompatButton
private lateinit var infoScreen: AppCompatButton
private var clickItem: AppCompatButton? = null
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
clickItem = null
val window = this.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.statusBarColor = this.resources.getColor(R.color.start)
infoScreen = findViewById(R.id.infoScreen)
playgame = findViewById(R.id.button)
playgame.setOnClickListener {
if (clickItem == null) {
clickItem = playgame.findViewById(R.id.button)
playgame.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
playgame.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clickItem = null
startActivity(Intent(this, PlayActivity::class.java))
Log.d("TTT","playga o'tdi")
}.start()
}.start()
}
}
infoScreen.setOnClickListener {
if (clickItem == null) {
clickItem = infoScreen.findViewById(R.id.info)
infoScreen.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
infoScreen.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clickItem = null
startActivity(Intent(this, InfoActivity::class.java))
}.start()
}.start()
}
}
}
} |
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/screen/InfoActivity.kt | 817649179 | package uz.boxodir.test2048game.screen
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import uz.boxodir.test2048game.R
class InfoActivity : AppCompatActivity() {
private var back: ImageView? = null
private lateinit var goback:ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_info)
back = null
goback = findViewById(R.id.back_menu)
val window = this.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.statusBarColor = this.resources.getColor(R.color.info)
findViewById<View>(R.id.back_menu).setOnClickListener { v: View? ->
if (back == null) {
back = goback
goback.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
goback.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
startActivity(Intent(this, MainActivity::class.java))
finish()
}.start()
}.start()
}
}
}
} |
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/screen/PlayActivity.kt | 3644211720 | package uz.boxodir.test2048game.screen
import android.annotation.SuppressLint
import android.app.Dialog
import android.os.Bundle
import android.util.Log
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.LinearLayoutCompat
import uz.boxodir.test2048game.R
import uz.boxodir.test2048game.model.SideEnum
import uz.boxodir.test2048game.repository.AppRepository
import uz.boxodir.test2048game.settings.Settings
import uz.boxodir.test2048game.utils.BackgroundUtil
import uz.boxodir.test2048game.utils.MyTouchListener
class PlayActivity : AppCompatActivity() {
private val items: MutableList<TextView> = ArrayList(16)
private lateinit var mainView: LinearLayoutCompat
private var clic: ImageView? = null
private var clicRestartDialog: AppCompatButton? = null
private var repository = AppRepository.getInstance()
private var settings: Settings = Settings.getInstance()
private val util = BackgroundUtil()
private lateinit var level: TextView
private var record = 0
private var clickBackCount = 0
private lateinit var home_icon: ImageView
@SuppressLint("MissingInflatedId", "ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
clic = null
clicRestartDialog = null
setContentView(R.layout.activity_play)
setContentView(R.layout.activity_play)
level = findViewById(R.id.txt_score)
mainView = findViewById(R.id.mainView)
home_icon = findViewById(R.id.home_icon)
val window = this.window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
window.statusBarColor = this.resources.getColor(R.color.gamescreen)
loadViews()
describeMatrixToViews()
loadTochLisener()
funtions()
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
private fun loadTochLisener() {
if (clickBackCount == 1 || !repository.isPlaying()) {
findViewById<ImageView>(R.id.back).alpha = 0.2f
findViewById<ImageView>(R.id.back).isClickable = false
}
val myTouchListener = MyTouchListener(this)
myTouchListener.setMyMovementSideListener {
findViewById<ImageView>(R.id.back).alpha = 1f
findViewById<ImageView>(R.id.back).isClickable = true
clickBackCount = 0
when (it) {
SideEnum.DOWN -> {
if (!repository.isClickable()) {
openGameOverDialog()
}
repository.setState(true)
repository.moveDown()
describeMatrixToViews()
}
SideEnum.UP -> {
if (!repository.isClickable()) {
openGameOverDialog()
}
repository.setState(true)
repository.moveUp()
describeMatrixToViews()
}
SideEnum.RIGHT -> {
if (!repository.isClickable()) {
openGameOverDialog()
}
repository.setState(true)
repository.moveToRight()
describeMatrixToViews()
}
SideEnum.LEFT -> {
if (!repository.isClickable()) {
openGameOverDialog()
}
repository.setState(true)
repository.moveToLeft()
describeMatrixToViews()
}
}
}
mainView.setOnTouchListener(myTouchListener)
}
fun openGameOverDialog() {
val gameOverDialog = Dialog(this)
gameOverDialog.setContentView(R.layout.gameover)
gameOverDialog.setCancelable(false)
gameOverDialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
gameOverDialog.findViewById<TextView>(R.id.textView3).text = repository.level.toString()
gameOverDialog.findViewById<ImageView>(R.id.imageView4).setOnClickListener {
repository.clear()
repository = AppRepository.getInstance()
describeMatrixToViews()
gameOverDialog.dismiss()
}
gameOverDialog.findViewById<ImageView>(R.id.imageView3).setOnClickListener {
repository.restart()
repository = AppRepository.getInstance()
gameOverDialog.dismiss()
finish()
}
gameOverDialog.show()
}
private fun loadViews() {
for (i in 0 until mainView.childCount) {
val linear = mainView.getChildAt(i) as LinearLayoutCompat
for (j in 0 until linear.childCount) {
items.add(linear.getChildAt(j) as TextView)
}
}
}
private fun funtions() {
findViewById<ImageView>(R.id.play_activity_restart).setOnClickListener {
if (clic == null) {
clic = findViewById<ImageView>(R.id.play_activity_restart)
findViewById<ImageView>(R.id.play_activity_restart).animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
findViewById<ImageView>(R.id.play_activity_restart).animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clic = null
showRestartGameDialog()
}.start()
}.start()
}
}
findViewById<ImageView>(R.id.back).setOnClickListener {
if (clic == null) {
clic = findViewById<ImageView>(R.id.back)
findViewById<ImageView>(R.id.back).animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
findViewById<ImageView>(R.id.back).animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clic = null
clickBackCount++
repository.backOldState()
describeMatrixToViews()
}.start()
}.start()
}
}
home_icon.setOnClickListener {
home_icon.setOnClickListener {
if (clic == null) {
clic = home_icon
home_icon.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
home_icon.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clic = null
Log.d("TTT","play finish bo'ldi")
finish()
}.start()
}.start()
}
}
}
}
private fun showRestartGameDialog() {
val restartDialog = Dialog(this)
restartDialog.setContentView(R.layout.gameover)
restartDialog.setCancelable(true)
restartDialog.window?.setBackgroundDrawableResource(android.R.color.transparent);
restartDialog.setContentView(R.layout.item_restart)
val yesBtn = restartDialog.findViewById(R.id.button) as AppCompatButton
val noBtn = restartDialog.findViewById(R.id.button2) as AppCompatButton
yesBtn.setOnClickListener {
if (clicRestartDialog == null) {
clicRestartDialog = yesBtn
yesBtn.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
yesBtn.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clicRestartDialog = null
repository.clear()
repository = AppRepository.getInstance()
describeMatrixToViews()
restartDialog.dismiss()
}
.start()
}
.start()
}
}
noBtn.setOnClickListener {
if (clicRestartDialog == null) {
clicRestartDialog = noBtn
noBtn.animate()
.scaleX(0.7f)
.setDuration(200)
.scaleY(0.7f)
.withEndAction {
noBtn.animate()
.setDuration(90)
.scaleY(1f)
.scaleX(1f)
.withEndAction {
clicRestartDialog = null
restartDialog.dismiss()
}.start()
}.start()
}
}
restartDialog.show()
}
@SuppressLint("ResourceAsColor")
private fun describeMatrixToViews() {
if (clickBackCount == 1 || !repository.isPlaying()) {
findViewById<ImageView>(R.id.back).alpha = 0.2f
findViewById<ImageView>(R.id.back).isClickable = false
}
var txt_best = findViewById<TextView>(R.id.txt_bestscore)
level.text = repository.level.toString()
record = txt_best.text.toString().toInt()
record = repository.getRecord()
if (repository.level > record) {
record = repository.level
}
txt_best.text = record.toString()
val _matrix = repository.matrix
for (i in _matrix.indices) {
for (j in _matrix[i].indices) {
items[i * _matrix.size + j].apply {
text = if (_matrix[i][j] == 0) ""
else _matrix[i][j].toString()
setBackgroundResource(util.colorByCount(_matrix[i][j]))
}
if (_matrix[i][j] == 16384) {
openGameOverDialog()
}
}
}
}
override fun onStop() {
super.onStop()
repository.saveRecord(record)
repository.saveItems()
}
} |
Legend_2048_Game/app/src/main/java/uz/boxodir/test2048game/model/SideEnum.kt | 1852745598 | package uz.boxodir.test2048game.model
enum class SideEnum {
LEFT, UP, RIGHT, DOWN
} |
PetLover/app/src/androidTest/java/com/example/petlover/ExampleInstrumentedTest.kt | 3419834747 | package com.example.petlover
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.petlover", appContext.packageName)
}
} |
PetLover/app/src/test/java/com/example/petlover/ExampleUnitTest.kt | 2014333515 | package com.example.petlover
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)
}
} |
PetLover/app/src/main/java/com/example/petlover/navigation/Routes.kt | 717678564 | package com.example.petlover.navigation
object Routes {
const val DETAILS_SCREEN = "WELCOME_SCREEN"
const val INPUT_USER_SCREEN = "INPUT_USER_SCREEN"
const val USER_NAME = "NAME"
const val PET_CHOOSEN = "PET_CHOOSEN"
} |
PetLover/app/src/main/java/com/example/petlover/navigation/PetLoverNavigationGraph.kt | 3594046009 | package com.example.petlover.navigation
import androidx.compose.runtime.Composable
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.petlover.presentation.ui.UserInputViewModel
import com.example.petlover.presentation.ui.view.UserInputScreen
import com.example.petlover.presentation.ui.view.DetailsScreen
@Composable
fun PetLoverNavigationGraph(
userInputViewModel: UserInputViewModel = viewModel()
) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = Routes.DETAILS_SCREEN) {
composable(Routes.INPUT_USER_SCREEN) {
UserInputScreen(
viewModel = userInputViewModel,
showDetailsScreen = {
navController.navigate(route = Routes.DETAILS_SCREEN
+ "/${it.first}/${it.second}")
}
)
}
composable(
route = "${Routes.DETAILS_SCREEN}/${Routes.USER_NAME}/${Routes.PET_CHOOSEN}",
arguments = listOf(
navArgument(name = Routes.USER_NAME) { type = NavType.StringType },
navArgument(name = Routes.PET_CHOOSEN) { type = NavType.StringType }
)
) {
val userName = it.arguments?.getString(Routes.USER_NAME)
val petChoosen = it.arguments?.getString(Routes.PET_CHOOSEN)
DetailsScreen(userName, petChoosen)
}
}
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/AnimalCard.kt | 3355132957 | package com.example.petlover.presentation.ui.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
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.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.petlover.R
@Composable
fun AnimalCard(
imagePath: Int,
selected: Boolean,
animalSelected: (animalName: String) -> Unit
) {
val localFocusManager = LocalFocusManager.current
Card(
shape = RoundedCornerShape(8.dp),
modifier = Modifier
.padding(24.dp)
.size(130.dp),
elevation = CardDefaults.cardElevation(4.dp)
) {
Box(
modifier = Modifier
.fillMaxSize()
.border(
width = 1.dp,
color = if (selected) Color.Green else Color.Transparent,
shape = RoundedCornerShape(8.dp)
)
)
Image(
modifier = Modifier
.padding(16.dp)
.wrapContentSize()
.clickable {
val animalName =
if (imagePath == R.drawable.ic_launcher_foreground) "Cat" else "Dog"
animalSelected(animalName)
localFocusManager.clearFocus()
},
painter = painterResource(id = imagePath),
contentDescription = "Animal Image"
)
}
}
@Preview(showBackground = true)
@Composable
fun AnimalCardPreview() {
AnimalCard(R.drawable.ic_launcher_foreground, true, { "Dog" })
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/TextBox.kt | 3062547555 | package com.example.petlover.presentation.ui.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun TextBox(title: String, descripton: String?) {
Column {
Text(
text = title,
fontSize = 20.sp
)
Spacer(modifier = Modifier.size(8.dp))
descripton?.let {
Text(
text = it,
fontSize = 16.sp,
color = Color.DarkGray
)
}
}
}
@Preview(showBackground = true)
@Composable
fun TextBoxPreview() {
TextBox(
"Bem vindo, PetLover!",
"Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum"
)
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/TopBar.kt | 1940280633 | package com.example.petlover.presentation.ui.components
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.petlover.R
@Composable
fun TopBar(value: String){
Row(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = value,
color = Color.Black,
fontWeight = FontWeight.Medium,
fontSize = 24.sp
)
Spacer(modifier = Modifier.weight(1f))
Image(
modifier = Modifier.size(80.dp),
painter = painterResource(id = R.drawable.ic_launcher_foreground),
contentDescription = null
)
}
}
@Preview(showBackground = true)
@Composable
fun TopBarPreview(){
TopBar("Hi, there")
} |
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/InputTextField.kt | 1397499068 | package com.example.petlover.presentation.ui.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.OutlinedTextField
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.platform.LocalFocusManager
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.sp
import com.example.petlover.R
@Composable
fun InputTextField(
onTextChange: (name: String) -> Unit
){
val localFocusManager = LocalFocusManager.current
var currentValue by remember{ mutableStateOf("") }
Column(
modifier = Modifier.fillMaxWidth()
) {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = currentValue,
onValueChange = {
currentValue = it
onTextChange(it)
},
placeholder = {
Text(
text = stringResource(R.string.input_text_field_component_enter_your_name),
fontSize = 18.sp
)
},
keyboardOptions = KeyboardOptions(
imeAction = ImeAction.Done
),
keyboardActions = KeyboardActions {
localFocusManager.clearFocus()
}
)
}
}
@Preview(showBackground = true)
@Composable
fun InputTextFieldPreview(){
// InputTextField()
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/ui/components/ButtonComponent.kt | 4279884887 | package com.example.petlover.presentation.ui.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun ButtonComponent(goToDetailsScreen: () -> Unit) {
Button(modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
onClick = { /*TODO*/ }
) {
Text(text = "Go to Details")
}
}
@Preview(showBackground = true)
@Composable
fun ButtonComponentPreview() {
ButtonComponent({})
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/ui/theme/Color.kt | 1692246380 | package com.example.petlover.presentation.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) |
PetLover/app/src/main/java/com/example/petlover/presentation/ui/theme/Theme.kt | 932242334 | package com.example.petlover.presentation.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 PetLoverTheme(
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
)
} |
PetLover/app/src/main/java/com/example/petlover/presentation/ui/theme/Type.kt | 2703877237 | package com.example.petlover.presentation.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
)
*/
) |
PetLover/app/src/main/java/com/example/petlover/presentation/ui/view/DetailsView.kt | 3712687176 | package com.example.petlover.presentation.ui.view
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.petlover.presentation.ui.components.TextBox
import com.example.petlover.presentation.ui.components.TopBar
@Composable
fun DetailsScreen(userName: String?, petChoosen: String?) {
Surface(modifier = Modifier.fillMaxSize()) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(18.dp)
) {
TopBar(value = "Welcome $userName")
TextBox(title = "Thank you for sharing your data!", descripton = null)
Spacer(modifier = Modifier.size(60.dp))
}
}
}
@Preview(showBackground = true)
@Composable
fun DetailsScreenPreview() {
DetailsScreen(userName = "username", petChoosen = "petchoosen")
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/ui/view/UserInputView.kt | 1947048717 | package com.example.petlover.presentation.ui.view
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.petlover.R
import com.example.petlover.presentation.ui.UserInputViewModel
import com.example.petlover.presentation.ui.components.AnimalCard
import com.example.petlover.presentation.ui.components.ButtonComponent
import com.example.petlover.presentation.ui.components.InputTextField
import com.example.petlover.presentation.ui.components.TextBox
import com.example.petlover.presentation.ui.components.TopBar
import com.example.petlover.presentation.ui.data.UserDataUiEvents
@Composable
fun UserInputScreen(
viewModel: UserInputViewModel,
showDetailsScreen: (valuePair: Pair<String, String>) -> Unit
) {
Surface(
modifier = Modifier.fillMaxSize()
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(18.dp)
) {
TopBar(value = "Hi, there")
TextBox(
title = "Bem vindo, PetLover!",
descripton = "Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum"
)
Spacer(modifier = Modifier.size(60.dp))
InputTextField(onTextChange = {
viewModel.onEvent(
UserDataUiEvents.UserNameInputed(it)
)
})
Spacer(modifier = Modifier.size(60.dp))
Text(text = "What do you want?")
Row(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
.align(Alignment.CenterHorizontally)
) {
AnimalCard(
imagePath = R.drawable.ic_launcher_foreground, animalSelected = {
viewModel.onEvent(
UserDataUiEvents.AnimalSelected(it)
)
}, selected = viewModel.uiState.value.petChoosen == "Cat"
)
AnimalCard(
imagePath = R.drawable.ic_launcher_background, animalSelected = {
viewModel.onEvent(
UserDataUiEvents.AnimalSelected(it)
)
}, selected = viewModel.uiState.value.petChoosen == "Dog"
)
}
Spacer(modifier = Modifier.weight(1f))
if (viewModel.isValidState()) {
ButtonComponent(
goToDetailsScreen = {
showDetailsScreen(
Pair(
viewModel.uiState.value.nameEntered,
viewModel.uiState.value.petChoosen
)
)
}
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun UserInputScreenPreview() {
UserInputScreen(UserInputViewModel(),{})
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/ui/data/UserDataUiEvents.kt | 1571362007 | package com.example.petlover.presentation.ui.data
sealed class UserDataUiEvents{
data class UserNameInputed(val name: String) : UserDataUiEvents()
data class AnimalSelected(val animalValue: String) : UserDataUiEvents()
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/ui/data/UserInputScreenState.kt | 3413594798 | package com.example.petlover.presentation.ui.data
data class UserInputScreenState(
var nameEntered: String = "",
var petChoosen: String = ""
) |
PetLover/app/src/main/java/com/example/petlover/presentation/ui/UserInputViewModel.kt | 3348107067 | package com.example.petlover.presentation.ui
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.example.petlover.presentation.ui.data.UserDataUiEvents
import com.example.petlover.presentation.ui.data.UserInputScreenState
class UserInputViewModel : ViewModel() {
var uiState = mutableStateOf(UserInputScreenState())
fun onEvent(event: UserDataUiEvents){
when(event){
is UserDataUiEvents.UserNameInputed -> {
uiState.value = uiState.value.copy(nameEntered = event.name)
}
is UserDataUiEvents.AnimalSelected -> {
uiState.value = uiState.value.copy(petChoosen = event.animalValue)
}
}
}
fun isValidState(): Boolean {
return uiState.value.nameEntered.isNotEmpty()
&& uiState.value.petChoosen.isNotEmpty()
}
}
|
PetLover/app/src/main/java/com/example/petlover/presentation/shared/MainActivity.kt | 69694235 | package com.example.petlover.presentation.shared
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.example.petlover.presentation.ui.theme.PetLoverTheme
import com.example.petlover.navigation.PetLoverNavigationGraph
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
installSplashScreen()
setContent {
PetLoverTheme {
PetLoverApp()
}
}
}
@Composable
fun PetLoverApp() {
PetLoverNavigationGraph()
}
}
|
MovilNavito/app/src/main/java/com/codelab/basiclayouts/ui/theme/Shape.kt | 4073031578 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codelab.basiclayouts.ui.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Shapes
import androidx.compose.ui.unit.dp
val shapes = Shapes(
small = RoundedCornerShape(4.dp),
medium = RoundedCornerShape(12.dp)
)
|
MovilNavito/app/src/main/java/com/codelab/basiclayouts/ui/theme/Color.kt | 3199454695 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codelab.basiclayouts.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF6B5C4D)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFF4DFCD)
val md_theme_light_onPrimaryContainer = Color(0xFF241A0E)
val md_theme_light_secondary = Color(0xFF635D59)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFEAE1DB)
val md_theme_light_onSecondaryContainer = Color(0xFF1F1B17)
val md_theme_light_tertiary = Color(0xFF5E5F58)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFE3E3DA)
val md_theme_light_onTertiaryContainer = Color(0xFF1B1C17)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFF5F0EE)
val md_theme_light_onBackground = Color(0xFF1D1B1A)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF1D1B1A)
val md_theme_light_surfaceVariant = Color(0xFFE7E1DE)
val md_theme_light_onSurfaceVariant = Color(0xFF494644)
val md_theme_light_outline = Color(0xFF7A7674)
val md_theme_light_inverseOnSurface = Color(0xFFF5F0EE)
val md_theme_dark_primary = Color(0xFFD7C3B1)
val md_theme_dark_onPrimary = Color(0xFF3A2E22)
val md_theme_dark_primaryContainer = Color(0xFF524437)
val md_theme_dark_onPrimaryContainer = Color(0xFFF4DFCD)
val md_theme_dark_secondary = Color(0xFFCDC5BF)
val md_theme_dark_onSecondary = Color(0xFF34302C)
val md_theme_dark_secondaryContainer = Color(0xFF4B4642)
val md_theme_dark_onSecondaryContainer = Color(0xFFEAE1DB)
val md_theme_dark_tertiary = Color(0xFFC7C7BE)
val md_theme_dark_onTertiary = Color(0xFF30312B)
val md_theme_dark_tertiaryContainer = Color(0xFF464741)
val md_theme_dark_onTertiaryContainer = Color(0xFFE3E3DA)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFB4AB)
val md_theme_dark_background = Color(0xFF32302F)
val md_theme_dark_onBackground = Color(0xFFE6E1E0)
val md_theme_dark_surface = Color(0xFF1D1B1A)
val md_theme_dark_onSurface = Color(0xFFE6E1E0)
val md_theme_dark_surfaceVariant = Color(0xFF494644)
val md_theme_dark_onSurfaceVariant = Color(0xFFE6E1E0)
val md_theme_dark_outline = Color(0xFF94908D)
|
MovilNavito/app/src/main/java/com/codelab/basiclayouts/ui/theme/Theme.kt | 1031957268 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codelab.basiclayouts.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
private val LightColors = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline
)
private val DarkColors = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline
)
@Composable
fun MySootheTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable() () -> Unit
) {
val colors = if (darkTheme) {
DarkColors
} else {
LightColors
}
MaterialTheme(
colorScheme = colors,
typography = typography,
shapes = shapes,
content = content
)
}
|
MovilNavito/app/src/main/java/com/codelab/basiclayouts/ui/theme/Type.kt | 1402908547 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codelab.basiclayouts.ui.theme
import androidx.compose.material3.Typography
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.style.TextAlign
import androidx.compose.ui.unit.sp
import com.codelab.basiclayouts.R
private val fontFamilyKulim = FontFamily(
listOf(
Font(
resId = R.font.kulim_park_regular
),
Font(
resId = R.font.kulim_park_light,
weight = FontWeight.Light
)
)
)
private val fontFamilyLato = FontFamily(
listOf(
Font(
resId = R.font.lato_regular
),
Font(
resId = R.font.lato_bold,
weight = FontWeight.Bold
)
)
)
val typography = Typography(
displayLarge = TextStyle(
fontFamily = fontFamilyKulim,
fontWeight = FontWeight.Light,
fontSize = 57.sp,
lineHeight = 64.sp,
letterSpacing = (-0.25).sp
),
displayMedium = TextStyle(
fontFamily = fontFamilyKulim,
fontSize = 45.sp,
lineHeight = 52.sp
),
displaySmall = TextStyle(
fontFamily = fontFamilyKulim,
fontSize = 36.sp,
lineHeight = 44.sp
),
titleMedium = TextStyle(
fontFamily = fontFamilyLato,
fontWeight = FontWeight(500),
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = (0.15).sp
),
bodySmall = TextStyle(
fontFamily = fontFamilyLato,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = (0.4).sp
),
bodyMedium = TextStyle(
fontFamily = fontFamilyLato,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = (0.25).sp
),
bodyLarge = TextStyle(
fontFamily = fontFamilyLato,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = (0.5).sp
),
labelMedium = TextStyle(
fontFamily = fontFamilyLato,
fontWeight = FontWeight(500),
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = (0.5).sp,
textAlign = TextAlign.Center
),
labelLarge = TextStyle(
fontFamily = fontFamilyLato,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = (0.1).sp
)
)
|
MovilNavito/app/src/main/java/com/codelab/basiclayouts/MainActivity.kt | 2662613131 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.codelab.basiclayouts
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.codelab.basiclayouts.ui.theme.MySootheTheme
import androidx.compose.material3.TextField
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.ui.res.stringResource
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.ui.res.painterResource
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.Alignment
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.Surface
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Spa
import androidx.compose.material3.Scaffold
import androidx.compose.material3.NavigationRail
import androidx.compose.material3.NavigationRailItem
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.material3.windowsizeclass.WindowSizeClass
import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass
import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi
import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass
class MainActivity : ComponentActivity() {
@OptIn(ExperimentalMaterial3WindowSizeClassApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val windowSizeClass = calculateWindowSizeClass(this)
MySootheApp(windowSizeClass)
}
}
}
// Step: Search bar - Modifiers
@Composable
fun SearchBar(
modifier: Modifier = Modifier
) {
TextField(
value = "",
onValueChange = {},
leadingIcon = {
Icon(
imageVector = Icons.Default.Search,
contentDescription = null
)
},
colors = TextFieldDefaults.colors(
unfocusedContainerColor = MaterialTheme.colorScheme.surface,
focusedContainerColor = MaterialTheme.colorScheme.surface
),
placeholder = {
Text(stringResource(R.string.placeholder_search))
},
modifier = modifier
.fillMaxWidth()
.heightIn(min = 56.dp)
)
}
// Step: Align your body - Alignment
@Composable
fun AlignYourBodyElement(
@DrawableRes drawable: Int,
@StringRes text: Int,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(drawable),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(88.dp)
.clip(CircleShape)
)
Text(
text = stringResource(text),
modifier = Modifier.paddingFromBaseline(top = 24.dp, bottom = 8.dp),
style = MaterialTheme.typography.bodyMedium
)
}
}
// Step: Favorite collection card - Material Surface
@Composable
fun FavoriteCollectionCard(
@DrawableRes drawable: Int,
@StringRes text: Int,
modifier: Modifier = Modifier
) {
Surface(
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.width(255.dp)
) {
Image(
painter = painterResource(drawable),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.size(80.dp)
)
Text(
text = stringResource(text),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(horizontal = 16.dp)
)
}
}
}
// Step: Align your body row - Arrangements
@Composable
fun AlignYourBodyRow(
modifier: Modifier = Modifier
) {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(horizontal = 16.dp),
modifier = modifier
) {
items(alignYourBodyData) { item ->
AlignYourBodyElement(item.drawable, item.text)
}
}
}
// Step: Favorite collections grid - LazyGrid
@Composable
fun FavoriteCollectionsGrid(
modifier: Modifier = Modifier
) {
LazyHorizontalGrid(
rows = GridCells.Fixed(2),
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = modifier.height(168.dp)
) {
items(favoriteCollectionsData) { item ->
FavoriteCollectionCard(item.drawable, item.text, Modifier.height(80.dp))
}
}
}
// Step: Home section - Slot APIs
@Composable
fun HomeSection(
@StringRes title: Int,
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Column(modifier) {
Text(
text = stringResource(title),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.paddingFromBaseline(top = 40.dp, bottom = 16.dp)
.padding(horizontal = 16.dp)
)
content()
}
}
// Step: Home screen - Scrolling
@Composable
fun HomeScreen(modifier: Modifier = Modifier) {
Column(
modifier
.verticalScroll(rememberScrollState())
) {
Spacer(Modifier.height(16.dp))
SearchBar(Modifier.padding(horizontal = 16.dp))
HomeSection(title = R.string.align_your_body) {
AlignYourBodyRow()
}
HomeSection(title = R.string.favorite_collections) {
FavoriteCollectionsGrid()
}
Spacer(Modifier.height(16.dp))
}
}
// Step: Bottom navigation - Material
@Composable
private fun SootheBottomNavigation(modifier: Modifier = Modifier) {
NavigationBar(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
modifier = modifier
) {
NavigationBarItem(
icon = {
Icon(
imageVector = Icons.Default.Spa,
contentDescription = null
)
},
label = {
Text(stringResource(R.string.bottom_navigation_home))
},
selected = true,
onClick = {}
)
NavigationBarItem(
icon = {
Icon(
imageVector = Icons.Default.AccountCircle,
contentDescription = null
)
},
label = {
Text(stringResource(R.string.bottom_navigation_profile))
},
selected = false,
onClick = {}
)
}
}
// Step: MySoothe App - Scaffold
@Composable
fun MySootheAppPortrait() {
MySootheTheme {
Scaffold(
bottomBar = { SootheBottomNavigation() }
) { padding ->
HomeScreen(Modifier.padding(padding))
}
}
}
// Step: Bottom navigation - Material
@Composable
private fun SootheNavigationRail(modifier: Modifier = Modifier) {
NavigationRail(
modifier = modifier.padding(start = 8.dp, end = 8.dp),
containerColor = MaterialTheme.colorScheme.background,
) {
Column(
modifier = modifier.fillMaxHeight(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
NavigationRailItem(
icon = {
Icon(
imageVector = Icons.Default.Spa,
contentDescription = null
)
},
label = {
Text(stringResource(R.string.bottom_navigation_home))
},
selected = true,
onClick = {}
)
Spacer(modifier = Modifier.height(8.dp))
NavigationRailItem(
icon = {
Icon(
imageVector = Icons.Default.AccountCircle,
contentDescription = null
)
},
label = {
Text(stringResource(R.string.bottom_navigation_profile))
},
selected = false,
onClick = {}
)
}
}
}
// Step: Landscape Mode
@Composable
fun MySootheAppLandscape() {
MySootheTheme {
Surface(color = MaterialTheme.colorScheme.background) {
Row {
SootheNavigationRail()
HomeScreen()
}
}
}
}
// Step: MySoothe App
@Composable
fun MySootheApp(windowSize: WindowSizeClass) {
when (windowSize.widthSizeClass) {
WindowWidthSizeClass.Compact -> {
MySootheAppPortrait()
}
WindowWidthSizeClass.Expanded -> {
MySootheAppLandscape()
}
}
}
private val alignYourBodyData = listOf(
R.drawable.ab1_inversions to R.string.ab1_inversions,
R.drawable.ab2_quick_yoga to R.string.ab2_quick_yoga,
R.drawable.ab3_stretching to R.string.ab3_stretching,
R.drawable.ab4_tabata to R.string.ab4_tabata,
R.drawable.ab5_hiit to R.string.ab5_hiit,
R.drawable.ab6_pre_natal_yoga to R.string.ab6_pre_natal_yoga,
R.drawable.ab7_gasero to R.string.ab7_gasero
).map { DrawableStringPair(it.first, it.second) }
private val favoriteCollectionsData = listOf(
R.drawable.fc1_short_mantras to R.string.fc1_short_mantras,
R.drawable.fc2_nature_meditations to R.string.fc2_nature_meditations,
R.drawable.fc3_stress_and_anxiety to R.string.fc3_stress_and_anxiety,
R.drawable.fc4_self_massage to R.string.fc4_self_massage,
R.drawable.fc5_overwhelmed to R.string.fc5_overwhelmed,
R.drawable.fc6_nightly_wind_down to R.string.fc6_nightly_wind_down
).map { DrawableStringPair(it.first, it.second) }
private data class DrawableStringPair(
@DrawableRes val drawable: Int,
@StringRes val text: Int
)
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
@Composable
fun SearchBarPreview() {
MySootheTheme { SearchBar(Modifier.padding(8.dp)) }
}
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
@Composable
fun AlignYourBodyElementPreview() {
MySootheTheme {
AlignYourBodyElement(
text = R.string.ab1_inversions,
drawable = R.drawable.ab1_inversions,
modifier = Modifier.padding(8.dp)
)
}
}
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
@Composable
fun FavoriteCollectionCardPreview() {
MySootheTheme {
FavoriteCollectionCard(
text = R.string.fc2_nature_meditations,
drawable = R.drawable.fc2_nature_meditations,
modifier = Modifier.padding(8.dp)
)
}
}
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
@Composable
fun FavoriteCollectionsGridPreview() {
MySootheTheme { FavoriteCollectionsGrid() }
}
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
@Composable
fun AlignYourBodyRowPreview() {
MySootheTheme { AlignYourBodyRow() }
}
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
@Composable
fun HomeSectionPreview() {
MySootheTheme {
HomeSection(R.string.align_your_body) {
AlignYourBodyRow()
}
}
}
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE, heightDp = 180)
@Composable
fun ScreenContentPreview() {
MySootheTheme { HomeScreen() }
}
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
@Composable
fun BottomNavigationPreview() {
MySootheTheme { SootheBottomNavigation(Modifier.padding(top = 24.dp)) }
}
@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
@Composable
fun NavigationRailPreview() {
MySootheTheme { SootheNavigationRail() }
}
@Preview(widthDp = 360, heightDp = 640)
@Composable
fun MySoothePortraitPreview() {
MySootheAppPortrait()
}
@Preview(widthDp = 640, heightDp = 360)
@Composable
fun MySootheLandscapePreview() {
MySootheAppLandscape()
}
|
MovilNavito/spotless/copyright.kt | 2813624007 | /*
* Copyright $YEAR The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
|
Kotlin_Kolkulator/src/123.kt | 4237529622 | fun main() {
while (true) {
val a = readLine()!!.toInt()
val b = readLine()!!.toInt()
val x = readLine()!!
if (x == "+") {
println(a + b)
}
if (x == "-") {
println(a - b)
}
if (x == "*") {
println(a * b)
}
if (x == "/") {
println(a / b)
}
println("Нажмите 1 чтобы выйти")
val z = readLine()!!
if (z == "1") {
print("Пока")
break
}
else{
continue
}
}}
|
CreditApplicationSystem/src/test/kotlin/me/dio/credit/application/system/CreditApplicationSystemApplicationTests.kt | 1010847126 | package me.dio.credit.application.system
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class CreditApplicationSystemApplicationTests {
@Test
fun contextLoads() {
}
}
|
CreditApplicationSystem/src/test/kotlin/me/dio/credit/application/system/repository/CreditRepositoryTest.kt | 696750062 | package me.dio.credit.application.system.repository
import me.dio.credit.application.system.entity.Address
import me.dio.credit.application.system.entity.Credit
import me.dio.credit.application.system.entity.Customer
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager
import org.springframework.test.context.ActiveProfiles
import java.math.BigDecimal
import java.time.LocalDate
import java.time.Month
import java.util.*
@ActiveProfiles("test")
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class CreditRepositoryTest {
@Autowired
lateinit var creditRepository: CreditRepository
@Autowired
lateinit var testEntityManager: TestEntityManager
private lateinit var customer: Customer
private lateinit var credit1: Credit
private lateinit var credit2: Credit
@BeforeEach
fun setup() {
customer = testEntityManager.merge(buildCustomer())
credit1 = testEntityManager.persist(buildCredit(customer = customer))
credit2 = testEntityManager.persist(buildCredit(customer = customer))
}
@Test
fun `should find credit code`() {
//given
val creditCode1 = UUID.fromString("aa547c0f-9a6a-451f-8c89-afddce916a29")
val creditCode2 = UUID.fromString("49f740be-46a7-449b-84e7-ff5b7986d7ef")
credit1.creditCode = creditCode1
credit2.creditCode = creditCode2
//when
val fakeCredit1: Credit = creditRepository.findByCreditCode(creditCode1)!!
val fakeCredit2: Credit = creditRepository.findByCreditCode(creditCode2)!!
//then
Assertions.assertThat(fakeCredit1).isNotNull
Assertions.assertThat(fakeCredit2).isNotNull
Assertions.assertThat(fakeCredit1).isSameAs(credit1)
Assertions.assertThat(fakeCredit2).isSameAs(credit2)
}
@Test
fun `should find all credits by customer id`() {
//given
val customerId: Long = 1L
//when
val creditList: List<Credit> = creditRepository.findAllByCustomerId(customerId)
//then
Assertions.assertThat(creditList).isNotEmpty
Assertions.assertThat(creditList.size).isEqualTo(2)
Assertions.assertThat(creditList).contains(credit1, credit2)
}
private fun buildCredit(
creditValue: BigDecimal = BigDecimal.valueOf(500.0),
dayFirstInstallment: LocalDate = LocalDate.of(2024, Month.FEBRUARY, 5),
numberOfInstallments: Int = 5,
customer: Customer
): Credit = Credit(
creditValue = creditValue,
dayFirstInstallment = dayFirstInstallment,
numberOfInstallments = numberOfInstallments,
customer = customer
)
private fun buildCustomer(
firstName: String = "Lucas",
lastName: String = "Tressoldi",
cpf: String = "431.194.775-59",
email: String = "[email protected]",
password: String = "123",
zipCode: String = "13844-023",
street: String = "Rua do Lucas",
income: BigDecimal = BigDecimal.valueOf(1000.0),
id: Long = 1L
) = Customer(
firstName = firstName,
lastName = lastName,
cpf = cpf,
email = email,
password = password,
address = Address(
zipCode = zipCode,
street = street
),
income = income,
id = id
)
} |
CreditApplicationSystem/src/test/kotlin/me/dio/credit/application/system/controller/CustomerResourceTest.kt | 3250886976 | package me.dio.credit.application.system.controller
import com.fasterxml.jackson.databind.ObjectMapper
import me.dio.credit.application.system.dto.CustomerDto
import me.dio.credit.application.system.dto.CustomerUpdateDto
import me.dio.credit.application.system.entity.Customer
import me.dio.credit.application.system.repository.CustomerRepository
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultHandlers
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import java.math.BigDecimal
import java.util.Random
@SpringBootTest
@ActiveProfiles("test")
@AutoConfigureMockMvc
@ContextConfiguration
class CustomerResourceTest {
@Autowired
private lateinit var customerRepository: CustomerRepository
@Autowired
private lateinit var mockMvc: MockMvc
@Autowired
private lateinit var objectMapper: ObjectMapper
companion object {
const val URL: String = "/api/customers"
}
@BeforeEach
fun setup() = customerRepository.deleteAll()
@AfterEach
fun tearDown() = customerRepository.deleteAll()
@Test
fun `should create customer and return 201 status`() {
//given
val customerDto: CustomerDto = buildCustomerDto()
val valueAsString: String = objectMapper.writeValueAsString(customerDto)
//when
//then
mockMvc.perform(
MockMvcRequestBuilders.post(URL)
.contentType(MediaType.APPLICATION_JSON)
.content(valueAsString)
).andExpect(MockMvcResultMatchers.status().isCreated).andDo(MockMvcResultHandlers.print())
}
@Test
fun `should not have a customer with same CPF and return 409 status`() {
//given
customerRepository.save(buildCustomerDto().toEntity())
val customerDto: CustomerDto = buildCustomerDto()
val valueAsString: String = objectMapper.writeValueAsString(customerDto)
//when
//then
mockMvc.perform(
MockMvcRequestBuilders.post(URL).contentType(MediaType.APPLICATION_JSON)
.content(valueAsString)
).andExpect(MockMvcResultMatchers.status().isConflict).andDo(MockMvcResultHandlers.print())
}
@Test
fun `should not have a customer with firstName empty and return 409 status`() {
//given
val customerDto: CustomerDto = buildCustomerDto(firstName = "")
val valueAsString: String = objectMapper.writeValueAsString(customerDto)
//when
//then
mockMvc.perform(
MockMvcRequestBuilders.post(URL).content(valueAsString)
.contentType(MediaType.APPLICATION_JSON)
).andExpect(MockMvcResultMatchers.status().isBadRequest)
.andDo(MockMvcResultHandlers.print())
}
@Test
fun `should find customer by id and return 200 status`() {
//given
val customer: Customer = customerRepository.save(buildCustomerDto().toEntity())
//when
//then
mockMvc.perform(
MockMvcRequestBuilders.get("$URL/${customer.id}")
.accept(MediaType.APPLICATION_JSON)
).andExpect(MockMvcResultMatchers.status().isOk).andDo(MockMvcResultHandlers.print())
}
@Test
fun `should not find customer with invalid id and return 400 status`() {
//given
val invalidId: Long = 2L
//when
//then
mockMvc.perform(MockMvcRequestBuilders.get("$URL/$invalidId").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isBadRequest).andDo(MockMvcResultHandlers.print())
}
@Test
fun `should delete customer by id`() {
//given
val customer: Customer = customerRepository.save(buildCustomerDto().toEntity())
//when
//then
mockMvc.perform(
MockMvcRequestBuilders.delete("$URL/${customer.id}")
.accept(MediaType.APPLICATION_JSON)
).andExpect(MockMvcResultMatchers.status().isNoContent).andDo(MockMvcResultHandlers.print())
}
@Test
fun `should not delete customer by id and return 400 status`() {
//given
val invalidId: Long = Random().nextLong()
//when
//then
mockMvc.perform(
MockMvcRequestBuilders.delete("$URL/${invalidId}")
.accept(MediaType.APPLICATION_JSON)
).andExpect(MockMvcResultMatchers.status().isBadRequest).andDo(MockMvcResultHandlers.print())
}
@Test
fun `should update a customer and return 200 status`() {
//given
val customer: Customer = customerRepository.save(buildCustomerDto().toEntity())
val customerUpdateDto: CustomerUpdateDto = buildCustomerUpdateDto()
val valueAsString: String = objectMapper.writeValueAsString(customerUpdateDto)
//when
//then
mockMvc.perform(
MockMvcRequestBuilders.patch("$URL?customerId=${customer.id}").contentType(MediaType.APPLICATION_JSON)
.content(valueAsString)
).andExpect(MockMvcResultMatchers.status().isOk).andDo(MockMvcResultHandlers.print())
}
@Test
fun `should not update a customer with invalid id and return 400 status`() {
//given
val invalidId: Long = Random().nextLong()
val customerUpdateDto: CustomerUpdateDto = buildCustomerUpdateDto()
val valueAsString: String = objectMapper.writeValueAsString(customerUpdateDto)
//when
//then
mockMvc.perform(
MockMvcRequestBuilders.patch("$URL?customerId=${invalidId}").contentType(MediaType.APPLICATION_JSON)
.content(valueAsString)
).andExpect(MockMvcResultMatchers.status().isBadRequest).andDo(MockMvcResultHandlers.print())
}
private fun buildCustomerDto(
firstName: String = "Lucas",
lastName: String = "Tressoldi",
cpf: String = "431.194.775-59",
email: String = "[email protected]",
income: BigDecimal = BigDecimal.valueOf(1000.0),
password: String = "123",
zipCode: String = "13844-023",
street: String = "Rua do Lucas"
) = CustomerDto(
firstName = firstName,
lastName = lastName,
cpf = cpf,
email = email,
income = income,
password = password,
zipCode = zipCode,
street = street
)
private fun buildCustomerUpdateDto(
firstName: String = "Lucas",
lastName: String = "Tressoldi",
income: BigDecimal = BigDecimal.valueOf(5000.0),
zipCode: String = "13844-023",
street: String = "Rua do Lucas"
): CustomerUpdateDto = CustomerUpdateDto(
firstName = firstName,
lastName = lastName,
income = income,
zipCode = zipCode,
street = street
)
} |
CreditApplicationSystem/src/test/kotlin/me/dio/credit/application/system/service/CustomerServiceTest.kt | 3308930399 | package me.dio.credit.application.system.service
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import io.mockk.just
import io.mockk.runs
import io.mockk.verify
import me.dio.credit.application.system.entity.Address
import me.dio.credit.application.system.entity.Customer
import me.dio.credit.application.system.exception.BusinessException
import me.dio.credit.application.system.repository.CustomerRepository
import me.dio.credit.application.system.service.impl.CustomerService
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.test.context.ActiveProfiles
import java.math.BigDecimal
import java.util.Optional
import java.util.Random
@ActiveProfiles("test")
@ExtendWith(MockKExtension::class)
class CustomerServiceTest {
@MockK lateinit var customerRepository: CustomerRepository
@InjectMockKs lateinit var customerService: CustomerService
@Test
fun `should create customer`(){
//given
val fakeCustomer: Customer = buildCustomer()
every { customerRepository.save(any()) } returns fakeCustomer
//when
val actual: Customer = customerService.save(fakeCustomer)
//then
Assertions.assertThat(actual).isNotNull
Assertions.assertThat(actual).isSameAs(fakeCustomer)
verify(exactly = 1) { customerRepository.save(fakeCustomer) }
}
@Test
fun `should find customer by id`() {
//given
val fakeId: Long = Random().nextLong()
val fakeCustomer: Customer = buildCustomer(id = fakeId)
every { customerRepository.findById(fakeId) } returns Optional.of(fakeCustomer)
//when
val actual: Customer = customerService.findById(fakeId)
//then
Assertions.assertThat(actual).isExactlyInstanceOf(Customer::class.java)
Assertions.assertThat(actual).isNotNull
Assertions.assertThat(actual).isSameAs(fakeCustomer)
verify(exactly = 1) { customerRepository.findById(fakeId) }
}
@Test
fun `should not find customer by invalid id and throw BusinessException()`() {
//given
val fakeId: Long = Random().nextLong()
every { customerRepository.findById(fakeId) } returns Optional.empty()
//when
//then
Assertions.assertThatExceptionOfType(BusinessException::class.java)
.isThrownBy { customerService.findById(fakeId) }
.withMessage("Id $fakeId not found.")
verify(exactly = 1) { customerRepository.findById(fakeId) }
}
@Test
fun `should delete customer by id`() {
//given
val fakeId: Long = Random().nextLong()
val fakeCustomer: Customer = buildCustomer(id = fakeId)
every { customerRepository.findById(fakeId) } returns Optional.of(fakeCustomer)
every { customerRepository.delete(fakeCustomer) } just runs
//when
customerService.delete(fakeId)
//then
verify(exactly = 1) { customerRepository.findById(fakeId) }
verify(exactly = 1) { customerRepository.delete(fakeCustomer) }
}
private fun buildCustomer(
firstName: String = "Lucas",
lastName: String = "Tressoldi",
cpf: String = "431.194.775-59",
email: String = "[email protected]",
password: String = "123",
zipCode: String = "13844-023",
street: String = "Rua do Lucas",
income: BigDecimal = BigDecimal.valueOf(1000.0),
id: Long = 1L
) = Customer(
firstName = firstName,
lastName = lastName,
cpf = cpf,
email = email,
password = password,
address = Address(
zipCode = zipCode,
street = street
),
income = income,
id = id
)
} |
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CreditDto.kt | 2844286333 | package me.dio.credit.application.system.dto
import jakarta.validation.constraints.Future
import jakarta.validation.constraints.NotNull
import me.dio.credit.application.system.entity.Credit
import me.dio.credit.application.system.entity.Customer
import java.math.BigDecimal
import java.time.LocalDate
data class CreditDto(
@field:NotNull(message = "Invalid input") val creditValue: BigDecimal,
@field:Future val dayFirstInstallment: LocalDate,
@field:NotNull(message = "Invalid input") val numberOfInstallments: Int,
@field:NotNull(message = "Invalid input") val customerId: Long
) {
fun toEntity(): Credit = Credit(
creditValue = this.creditValue,
dayFirstInstallment = this.dayFirstInstallment,
numberOfInstallments = this.numberOfInstallments,
customer = Customer(id = this.customerId)
)
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CustomerDto.kt | 1388614439 | package me.dio.credit.application.system.dto
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotEmpty
import jakarta.validation.constraints.NotNull
import me.dio.credit.application.system.entity.Address
import me.dio.credit.application.system.entity.Customer
import org.hibernate.validator.constraints.br.CPF
import java.math.BigDecimal
data class CustomerDto(
@field:NotEmpty(message = "Invalid input") val firstName: String,
@field:NotEmpty(message = "Invalid input") val lastName: String,
@field:NotEmpty(message = "Invalid input")
@field:CPF(message = "Invalid CPF") val cpf: String,
@field:NotNull(message = "Invalid input") val income: BigDecimal,
@field:NotEmpty(message = "Invalid input")
@field:Email(message = "Invalid email") val email: String,
@field:NotEmpty(message = "Invalid input") val password: String,
@field:NotEmpty(message = "Invalid input") val zipCode: String,
@field:NotEmpty(message = "Invalid input") val street: String
) {
fun toEntity(): Customer = Customer(
firstName = this.firstName,
lastName = this.lastName,
cpf = this.cpf,
income = this.income,
email = this.email,
password = this.password,
address = Address(zipCode = this.zipCode, street = this.street)
)
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CreditView.kt | 2922217574 | package me.dio.credit.application.system.dto
import me.dio.credit.application.system.entity.Credit
import me.dio.credit.application.system.enummeration.Status
import java.math.BigDecimal
import java.util.UUID
data class CreditView(
val creditCode: UUID,
val creditValue: BigDecimal,
val numberOfInstallments: Int,
val status: Status,
val emailCustomer: String?,
val incomeCustomer: BigDecimal?
) {
constructor(credit: Credit) : this(
creditCode = credit.creditCode,
creditValue = credit.creditValue,
numberOfInstallments = credit.numberOfInstallments,
status = credit.status,
emailCustomer = credit.customer?.email,
incomeCustomer = credit.customer?.income
)
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CustomerUpdateDto.kt | 507126925 | package me.dio.credit.application.system.dto
import jakarta.validation.constraints.NotEmpty
import jakarta.validation.constraints.NotNull
import me.dio.credit.application.system.entity.Customer
import java.math.BigDecimal
data class CustomerUpdateDto(
@field:NotEmpty(message = "Invalid input") val firstName: String,
@field:NotEmpty(message = "Invalid input") val lastName: String,
@field:NotNull(message = "Invalid input") val income: BigDecimal,
@field:NotEmpty(message = "Invalid input") val zipCode: String,
@field:NotEmpty(message = "Invalid input") val street: String
) {
fun toEntity(customer: Customer): Customer {
customer.firstName = this.firstName
customer.lastName = this.lastName
customer.income = this.income
customer.address.zipCode = this.zipCode
customer.address.street = this.street
return customer
}
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CreditViewList.kt | 2583717214 | package me.dio.credit.application.system.dto
import me.dio.credit.application.system.entity.Credit
import java.math.BigDecimal
import java.util.UUID
data class CreditViewList(
val creditCode: UUID,
val creditValue: BigDecimal,
val numberOfInstallments: Int
) {
constructor(credit: Credit) : this(
creditCode = credit.creditCode,
creditValue = credit.creditValue,
numberOfInstallments = credit.numberOfInstallments
)
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/dto/CustomerView.kt | 2856124615 | package me.dio.credit.application.system.dto
import me.dio.credit.application.system.entity.Customer
import java.math.BigDecimal
data class CustomerView(
val firstName: String,
val lastName: String,
val cpf: String,
val income: BigDecimal,
val email: String,
val zipCode: String,
val street: String,
val id: Long?
) {
constructor(customer: Customer): this (
firstName = customer.firstName,
lastName = customer.lastName,
cpf = customer.cpf,
income = customer.income,
email = customer.email,
zipCode = customer.address.zipCode,
street = customer.address.street,
id = customer.id
)
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/configuration/Swagger3Config.kt | 3756490166 | package me.dio.credit.application.system.configuration
import org.springdoc.core.models.GroupedOpenApi
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
class Swagger3Config {
@Bean
fun publicApi(): GroupedOpenApi? {
return GroupedOpenApi.builder().group("springcreditapplicationsystem-public")
.pathsToMatch("/api/customers/**", "/api/credits/**").build()
}
} |
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/repository/CreditRepository.kt | 4028667871 | package me.dio.credit.application.system.repository
import me.dio.credit.application.system.entity.Credit
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.util.UUID
@Repository
interface CreditRepository: JpaRepository<Credit, Long> {
fun findByCreditCode(creditCode: UUID): Credit?
@Query(value = "SELECT * FROM CREDIT WHERE CUSTOMER_ID = ?1", nativeQuery = true)
fun findAllByCustomerId(customerId: Long): List<Credit>
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/repository/CustomerRepository.kt | 2917125201 | package me.dio.credit.application.system.repository
import me.dio.credit.application.system.entity.Customer
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
@Repository
interface CustomerRepository: JpaRepository<Customer, Long>
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/entity/Credit.kt | 1186588665 | package me.dio.credit.application.system.entity
import jakarta.persistence.*
import me.dio.credit.application.system.enummeration.Status
import java.math.BigDecimal
import java.time.LocalDate
import java.util.UUID
@Entity
data class Credit(
@Column(nullable = false, unique = true) var creditCode: UUID = UUID.randomUUID(),
@Column(nullable = false) val creditValue: BigDecimal = BigDecimal.ZERO,
@Column(nullable = false) val dayFirstInstallment: LocalDate,
@Column(nullable = false) val numberOfInstallments: Int = 0,
@Enumerated val status: Status = Status.IN_PROGRESS,
@ManyToOne var customer: Customer? = null,
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null
)
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/entity/Customer.kt | 1123135062 | package me.dio.credit.application.system.entity
import jakarta.persistence.*
import java.math.BigDecimal
@Entity
data class Customer(
@Column(nullable = false) var firstName: String = "",
@Column(nullable = false) var lastName: String = "",
@Column(nullable = false, unique = true) var email: String = "",
@Column(nullable = false, unique = true) var cpf: String = "",
@Column(nullable = false) var income: BigDecimal = BigDecimal.ZERO,
@Column(nullable = false) var password: String = "",
@Column(nullable = false) @Embedded var address: Address = Address(),
@Column(nullable = false) @OneToMany(fetch = FetchType.LAZY, cascade = [CascadeType.REMOVE, CascadeType.PERSIST],
mappedBy = "customer") var credits: List<Credit> = mutableListOf(),
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long? = null
)
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/entity/Address.kt | 4051917962 | package me.dio.credit.application.system.entity
import jakarta.persistence.Column
import jakarta.persistence.Embeddable
@Embeddable
data class Address(
@Column(nullable = false) var zipCode: String = "",
@Column(nullable = false) var street: String = ""
)
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/controller/CustomerResource.kt | 3448832263 | package me.dio.credit.application.system.controller
import jakarta.validation.Valid
import me.dio.credit.application.system.dto.CustomerDto
import me.dio.credit.application.system.dto.CustomerUpdateDto
import me.dio.credit.application.system.dto.CustomerView
import me.dio.credit.application.system.entity.Customer
import me.dio.credit.application.system.service.impl.CustomerService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PatchMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/customers")
class CustomerResource(private val customerService: CustomerService) {
@PostMapping
fun saveCustomer(@RequestBody @Valid customerDto: CustomerDto): ResponseEntity<String> {
val savedCustomer = this.customerService.save(customerDto.toEntity())
return ResponseEntity.status(HttpStatus.CREATED).body("Customer ${savedCustomer.email} saved!")
}
@GetMapping("/{id}")
fun findById(@PathVariable id: Long): ResponseEntity<CustomerView> {
val customer: Customer = this.customerService.findById(id)
return ResponseEntity.status(HttpStatus.OK).body(CustomerView(customer))
}
@DeleteMapping("/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun delete(@PathVariable id: Long) = this.customerService.delete(id)
@PatchMapping
fun updateCustomer(
@RequestParam(value = "customerId") id: Long,
@RequestBody @Valid customerUpdateDto: CustomerUpdateDto
): ResponseEntity<CustomerView> {
val customer: Customer = this.customerService.findById(id)
val customerToUpdate = customerUpdateDto.toEntity(customer)
val customerUpdated = this.customerService.save(customerToUpdate)
return ResponseEntity.status(HttpStatus.OK).body(CustomerView(customerUpdated))
}
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/controller/CreditResource.kt | 3245051678 | package me.dio.credit.application.system.controller
import jakarta.validation.Valid
import me.dio.credit.application.system.dto.CreditDto
import me.dio.credit.application.system.dto.CreditView
import me.dio.credit.application.system.dto.CreditViewList
import me.dio.credit.application.system.entity.Credit
import me.dio.credit.application.system.service.impl.CreditService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.UUID
import java.util.stream.Collectors
@RestController
@RequestMapping("/api/credits")
class CreditResource(
private val creditService: CreditService
) {
@PostMapping
fun saveCredit(@RequestBody @Valid creditDto: CreditDto): ResponseEntity<String> {
val credit = this.creditService.save(creditDto.toEntity())
return ResponseEntity.status(HttpStatus.CREATED)
.body("Credit ${credit.creditCode} - Customer ${credit.customer?.firstName} saved!")
}
@GetMapping
fun findAllByCustomerId(@RequestParam(value = "customerId") customerId: Long): ResponseEntity<List<CreditViewList>> {
val creditViewList: List<CreditViewList> = this.creditService.findAllByCustomer(customerId).stream()
.map { credit: Credit -> CreditViewList(credit) }.collect(Collectors.toList())
return ResponseEntity.status(HttpStatus.OK).body(creditViewList)
}
@GetMapping("/{creditCode}")
fun findByCreditCode(
@RequestParam(value = "customerId") customerId: Long,
@PathVariable creditCode: UUID
): ResponseEntity<CreditView> {
val credit: Credit = this.creditService.findByCreditCode(customerId, creditCode)
return ResponseEntity.status(HttpStatus.OK).body(CreditView(credit))
}
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/enummeration/Status.kt | 2973033076 | package me.dio.credit.application.system.enummeration
enum class Status {
IN_PROGRESS, APPROVED, REJECTED
}
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/service/impl/CustomerService.kt | 2820511469 | package me.dio.credit.application.system.service.impl
import me.dio.credit.application.system.entity.Customer
import me.dio.credit.application.system.exception.BusinessException
import me.dio.credit.application.system.repository.CustomerRepository
import me.dio.credit.application.system.service.ICustomerService
import org.springframework.stereotype.Service
@Service
class CustomerService(private val customerRepository: CustomerRepository) : ICustomerService {
override fun save(customer: Customer): Customer = this.customerRepository.save(customer)
override fun findById(id: Long): Customer = this.customerRepository.findById(id).orElseThrow {
throw BusinessException("Id $id not found.")
}
override fun delete(id: Long) {
val customer: Customer = this.findById(id)
this.customerRepository.delete(customer)
}
} |
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/service/impl/CreditService.kt | 4187476571 | package me.dio.credit.application.system.service.impl
import me.dio.credit.application.system.entity.Credit
import me.dio.credit.application.system.exception.BusinessException
import me.dio.credit.application.system.repository.CreditRepository
import me.dio.credit.application.system.service.ICreditService
import org.springframework.stereotype.Service
import java.util.*
@Service
class CreditService(
private val creditRepository: CreditRepository,
private val customerService: CustomerService
) : ICreditService {
override fun save(credit: Credit): Credit {
credit.apply {
customer = customerService.findById(credit.customer?.id!!)
}
return this.creditRepository.save(credit)
}
override fun findAllByCustomer(customerId: Long): List<Credit> =
this.creditRepository.findAllByCustomerId(customerId)
override fun findByCreditCode(customerId: Long, creditCode: UUID): Credit {
val credit: Credit = (this.creditRepository.findByCreditCode(creditCode)
?: throw BusinessException("CreditCode $creditCode not found."))
return if (credit.customer?.id == customerId) credit else throw IllegalArgumentException(
"Something wrong. Please, contact admin."
)
}
} |
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/service/ICustomerService.kt | 3328967271 | package me.dio.credit.application.system.service
import me.dio.credit.application.system.entity.Customer
interface ICustomerService {
fun save(customer: Customer): Customer
fun findById(id: Long): Customer
fun delete(id: Long)
} |
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/service/ICreditService.kt | 2657315617 | package me.dio.credit.application.system.service
import me.dio.credit.application.system.entity.Credit
import java.util.*
interface ICreditService {
fun save(credit: Credit): Credit
fun findAllByCustomer(customerId: Long): List<Credit>
fun findByCreditCode(customerId: Long, creditCode: UUID): Credit
} |
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/exception/RestExceptionHandler.kt | 3258162004 | package me.dio.credit.application.system.exception
import org.springframework.dao.DataAccessException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.validation.FieldError
import org.springframework.validation.ObjectError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import java.time.LocalDateTime
@RestControllerAdvice
class RestExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handlerValidException(ex: MethodArgumentNotValidException): ResponseEntity<ExceptionDetails> {
val errors: MutableMap<String, String?> = HashMap()
ex.bindingResult.allErrors.stream().forEach { err: ObjectError ->
val fieldName: String = (err as FieldError).field
val messageError: String? = err.defaultMessage
errors[fieldName] = messageError
}
return ResponseEntity(
ExceptionDetails(
title = "Bad Request! Consult the documentation.",
timestamp = LocalDateTime.now(),
status = HttpStatus.BAD_REQUEST.value(),
exception = ex.javaClass.toString(),
details = errors
), HttpStatus.BAD_REQUEST
)
}
@ExceptionHandler(DataAccessException::class)
fun handlerValidException(ex: DataAccessException): ResponseEntity<ExceptionDetails> {
return ResponseEntity(
ExceptionDetails(
title = "Conflict! Consult the documentation.",
timestamp = LocalDateTime.now(),
status = HttpStatus.CONFLICT.value(),
exception = ex.javaClass.toString(),
details = mutableMapOf(ex.cause.toString() to ex.message)
), HttpStatus.CONFLICT
)
}
@ExceptionHandler(BusinessException::class)
fun handlerValidException(ex: BusinessException): ResponseEntity<ExceptionDetails> {
return ResponseEntity(
ExceptionDetails(
title = "Bad request! Consult the documentation.",
timestamp = LocalDateTime.now(),
status = HttpStatus.BAD_REQUEST.value(),
exception = ex.javaClass.toString(),
details = mutableMapOf(ex.cause.toString() to ex.message)
), HttpStatus.BAD_REQUEST
)
}
@ExceptionHandler(IllegalArgumentException::class)
fun handlerValidException(ex: IllegalArgumentException): ResponseEntity<ExceptionDetails> {
return ResponseEntity(
ExceptionDetails(
title = "Bad request! Consult the documentation.",
timestamp = LocalDateTime.now(),
status = HttpStatus.BAD_REQUEST.value(),
exception = ex.javaClass.toString(),
details = mutableMapOf(ex.cause.toString() to ex.message)
), HttpStatus.BAD_REQUEST
)
}
} |
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/exception/BusinessException.kt | 1587394322 | package me.dio.credit.application.system.exception
data class BusinessException(override val message: String?) : RuntimeException(message)
|
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/exception/ExceptionDetails.kt | 3539025457 | package me.dio.credit.application.system.exception
import java.time.LocalDateTime
class ExceptionDetails(
val title: String,
val timestamp: LocalDateTime,
val status: Int,
val exception: String,
val details: MutableMap<String, String?>
) {
} |
CreditApplicationSystem/src/main/kotlin/me/dio/credit/application/system/CreditApplicationSystemApplication.kt | 3438845359 | package me.dio.credit.application.system
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class CreditApplicationSystemApplication
fun main(args: Array<String>) {
runApplication<CreditApplicationSystemApplication>(*args)
}
|
CircleCircleDotDot/app/src/androidTest/java/com/example/circlecircledotdot/ExampleInstrumentedTest.kt | 4250219072 | package com.example.circlecircledotdot
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.circlecircledotdot", appContext.packageName)
}
} |
CircleCircleDotDot/app/src/test/java/com/example/circlecircledotdot/ExampleUnitTest.kt | 4036978480 | package com.example.circlecircledotdot
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)
}
} |
CircleCircleDotDot/app/src/main/java/com/example/circlecircledotdot/MainActivity.kt | 3964995016 | package com.example.circlecircledotdot
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, InputFragment.newInstance())
.commitNow()
}
}
}
|
CircleCircleDotDot/app/src/main/java/com/example/circlecircledotdot/DisplayFragment.kt | 3860431655 | package com.example.circlecircledotdot
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import java.util.Random
class DisplayFragment : Fragment() {
companion object {
private const val COLOR_KEY = "color"
fun newInstance(color: Int): DisplayFragment {
val fragment = DisplayFragment()
val args = Bundle()
args.putInt(COLOR_KEY, color)
fragment.arguments = args
return fragment
}
}
private var color: Int = Color.BLACK // Default color if no argument is provided
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_display, container, false)
val surfaceView = view.findViewById<SurfaceView>(R.id.surfaceView)
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
// Start drawing on surface created
drawCircle(holder)
}
override fun surfaceChanged(
holder: SurfaceHolder,
format: Int,
width: Int,
height: Int
) {
// Respond to surface changes if needed
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
// Handle surface destruction if needed
}
})
return view
}
private fun drawCircle(holder: SurfaceHolder) {
val canvas: Canvas? = holder.lockCanvas()
if (canvas != null) {
canvas.drawColor(Color.WHITE) // Clear canvas
val paint = Paint().apply {
color = [email protected]
isAntiAlias = true
}
// X 1.05f längst höger 30f längst vänster
// y 1.03f = botten 20 f högst
val random= Random()
val screenWidth = canvas.width.toFloat()
val screenHeight = canvas.height.toFloat()
val centerX = random.nextFloat()*screenWidth
val centerY = random.nextFloat()*screenHeight
val radius = 50f
// val centerX = canvas.width / 20f
// val centerY = canvas.height / 30f
canvas.drawCircle(centerX, centerY, radius, paint)
holder.unlockCanvasAndPost(canvas)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
color = it.getInt(COLOR_KEY)
}
}
}
|
CircleCircleDotDot/app/src/main/java/com/example/circlecircledotdot/InputFragment.kt | 2392581252 | package com.example.circlecircledotdot
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import kotlin.random.Random
class InputFragment : Fragment() {
companion object {
fun newInstance() = InputFragment()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_input, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val btnCreate = view.findViewById<Button>(R.id.btn_create)
btnCreate.setOnClickListener {
val randomColor = getRandomColor()
val displayFragment = DisplayFragment.newInstance(randomColor)
activity?.supportFragmentManager?.beginTransaction()
?.replace(R.id.container, displayFragment)
?.addToBackStack(null)
?.commit()
}
}
private fun getRandomColor(): Int {
val random = Random
return android.graphics.Color.argb(
255,
random.nextInt(256),
random.nextInt(256),
random.nextInt(256)
)
}
}
|
advent_of_code23/src/main/kotlin/org/rgoussey/aoc2023/day4/Main.kt | 3916953134 | package org.rgoussey.aoc2023.day4
import java.io.File
import java.util.stream.Collectors
fun main() {
val lines = File({}.javaClass.getResource("/day4/input.txt")!!.toURI()).readLines();
process(lines);
}
fun process(lines: List<String>) {
val cards = lines.stream().map { line ->
Card(line)
}.toList()
var sum = 0;
cards.forEach { card ->
run {
val score = card.getScore()
println("score $score")
sum += score
}
}
print(sum)
}
class Card(line: String) {
private var duplicateNumbers: Set<Int>
private val losingNumbers: Set<Int>
private val winningNumbers: Set<Int>
init {
val numbers = line.split(":")[1].split("|")
winningNumbers = parseNumbers(numbers[0])
losingNumbers = parseNumbers(numbers[1])
duplicateNumbers =
losingNumbers.stream().filter(winningNumbers::contains).collect(Collectors.toSet())
}
fun getScore(): Int {
val size = duplicateNumbers.size
return if (size <= 1) {
size;
} else {
1 shl size - 1
}
}
private fun parseNumbers(line: String): Set<Int> {
val result: MutableSet<Int> = HashSet();
val numbers = line.split(" ")
numbers.forEach { number ->
run {
try {
result.add(number.toInt())
} catch (e: Exception) {
//Ignore
}
}
}
return result;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.