path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
Product-image-search/app/src/main/java/com/google/codelabs/productimagesearch/api/ProductSearchAPIClient.kt
3775304308
/** * Copyright 2021 Google LLC * * 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.google.codelabs.productimagesearch.api import android.content.Context import android.graphics.Bitmap import android.util.Base64 import android.util.Log import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.TaskCompletionSource import com.google.android.gms.tasks.Tasks import com.google.codelabs.productimagesearch.ProductSearchActivity import com.google.gson.Gson import com.google.gson.JsonSyntaxException import org.json.JSONObject import java.io.ByteArrayOutputStream class ProductSearchAPIClient(context: Context){ companion object { const val VISION_API_PRODUCT_MAX_RESULT = 5 // Define the product search backend // Option 1: Use the demo project that we have already deployed for you const val VISION_API_URL = "https://us-central1-odml-codelabs.cloudfunctions.net/productSearch" const val VISION_API_KEY = "" const val VISION_API_PROJECT_ID = "odml-codelabs" const val VISION_API_LOCATION_ID = "us-east1" const val VISION_API_PRODUCT_SET_ID = "product_set0" // Option 2: Go through the Vision API Product Search quickstart and deploy to your project. // Fill in the const below with your project info. // const val VISION_API_URL = "https://vision.googleapis.com/v1" // const val VISION_API_KEY = "YOUR_API_KEY" // const val VISION_API_PROJECT_ID = "YOUR_PROJECT_ID" // const val VISION_API_LOCATION_ID = "YOUR_LOCATION_ID" // const val VISION_API_PRODUCT_SET_ID = "YOUR_PRODUCT_SET_ID" } // Instantiate the RequestQueue. private val requestQueue = Volley.newRequestQueue(context) /** * Convert an image to its Base64 representation */ private fun convertBitmapToBase64(bitmap: Bitmap): String { val byteArrayOutputStream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream) val byteArray: ByteArray = byteArrayOutputStream.toByteArray() return Base64.encodeToString(byteArray, Base64.DEFAULT) } /** * Use Product Search API to search with the given query image * Call the projects.locations.images.annotate endpoint. */ fun annotateImage(image: Bitmap): Task<List<ProductSearchResult>> { // Initialization to use the Task API val apiSource = TaskCompletionSource<List<ProductSearchResult>>() val apiTask = apiSource.task // Convert the query image to its Base64 representation to call the Product Search API. val base64: String = convertBitmapToBase64(image) // Craft the request body JSON. val requestJson = """ { "requests": [ { "image": { "content": """".trimIndent() + base64 + """" }, "features": [ { "type": "PRODUCT_SEARCH", "maxResults": $VISION_API_PRODUCT_MAX_RESULT } ], "imageContext": { "productSearchParams": { "productSet": "projects/${VISION_API_PROJECT_ID}/locations/${VISION_API_LOCATION_ID}/productSets/${VISION_API_PRODUCT_SET_ID}", "productCategories": [ "apparel-v2" ] } } } ] } """.trimIndent() // Add a new request to the queue requestQueue.add(object : JsonObjectRequest( Method.POST, "$VISION_API_URL/images:annotate?key=$VISION_API_KEY", JSONObject(requestJson), { response -> // Parse the API JSON response to a list of ProductSearchResult object/ val productList = apiResponseToObject(response) // Return the list. // Loop through the product list and create tasks to load reference images. // We will call the projects.locations.products.referenceImages.get endpoint // for each product. val fetchReferenceImageTasks = productList.map { fetchReferenceImage(it) } // When all reference image fetches have completed, // return the ProductSearchResult list Tasks.whenAllComplete(fetchReferenceImageTasks) // Return the list of ProductSearchResult with product images' HTTP URLs. .addOnSuccessListener { apiSource.setResult(productList) } // An error occurred so returns it to the caller. .addOnFailureListener { apiSource.setException(it) } }, // Return the error { error -> apiSource.setException(error) } ) { override fun getBodyContentType() = "application/json" }.apply { setShouldCache(false) }) return apiTask } /** * Fetch and transform product image * Call the projects.locations.products.referenceImages.get endpoint */ private fun fetchReferenceImage(searchResult: ProductSearchResult): Task<ProductSearchResult> { // Initialization to use the Task API val apiSource = TaskCompletionSource<ProductSearchResult>() val apiTask = apiSource.task // Craft the API request to get details about the reference image of the product val stringRequest = object : StringRequest( Method.GET, "$VISION_API_URL/${searchResult.imageId}?key=$VISION_API_KEY", { response -> val responseJson = JSONObject(response) val gcsUri = responseJson.getString("uri") // Convert the GCS URL to its HTTPS representation val httpUri = gcsUri.replace("gs://", "https://storage.googleapis.com/") // Save the HTTPS URL to the search result object searchResult.imageUri = httpUri // Invoke the listener to continue with processing the API response (eg. show on UI) apiSource.setResult(searchResult) }, { error -> apiSource.setException(error) } ) { override fun getBodyContentType(): String { return "application/json; charset=utf-8" } } Log.d(ProductSearchActivity.TAG, "Sending API request.") // Add the request to the RequestQueue. requestQueue.add(stringRequest) return apiTask } /** * Convert the JSON API response to a list of ProductSearchResult objects */ @Throws(JsonSyntaxException::class) private fun apiResponseToObject(response: JSONObject): List<ProductSearchResult> { // Parse response JSON string into objects. val productSearchResults = mutableListOf<ProductSearchResult>() val searchResult = Gson().fromJson(response.toString(), SearchResultResponse::class.java) Log.d(ProductSearchActivity.TAG, "results: $searchResult") searchResult.responses?.get(0)?.productSearchResults?.results?.forEach { result -> productSearchResults.add( ProductSearchResult( result.image, result.score, result.product.productLabels.joinToString { "${it.key} - ${it.value}" }, result.product.name ) ) } return productSearchResults } }
Product-image-search/app/src/main/java/com/google/codelabs/productimagesearch/ImageClickableView.kt
293288338
/** * Copyright 2021 Google LLC * * 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.google.codelabs.productimagesearch import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.util.AttributeSet import android.util.Log import android.view.MotionEvent import androidx.appcompat.widget.AppCompatImageView import com.google.mlkit.vision.objects.DetectedObject import kotlin.math.abs import kotlin.math.max import kotlin.math.pow /** * Customize ImageView which can be clickable on some Detection Result Bound. */ class ImageClickableView : AppCompatImageView { companion object { private const val TAG = "ImageClickableView" private const val CLICKABLE_RADIUS = 40f private const val SHADOW_RADIUS = 10f } private val dotPaint = createDotPaint() private var onObjectClickListener: ((cropBitmap: Bitmap) -> Unit)? = null // This variable is used to hold the actual size of bounding box detection result due to // the ratio might changed after Bitmap fill into ImageView private var transformedResults = listOf<TransformedDetectionResult>() constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) /** * Callback when user click to detection result rectangle. */ fun setOnObjectClickListener(listener: ((objectImage: Bitmap) -> Unit)) { this.onObjectClickListener = listener } /** * Draw white circle at the center of each detected object on the image */ fun drawDetectionResults(results: List<DetectedObject>) { (drawable as? BitmapDrawable)?.bitmap?.let { srcImage -> // Get scale size based width/height val scaleFactor = max(srcImage.width / width.toFloat(), srcImage.height / height.toFloat()) // Calculate the total padding (based center inside scale type) val diffWidth = abs(width - srcImage.width / scaleFactor) / 2 val diffHeight = abs(height - srcImage.height / scaleFactor) / 2 // Transform the original Bounding Box to actual bounding box based the display size of ImageView. transformedResults = results.map { result -> // Calculate to create new coordinates of Rectangle Box match on ImageView. val actualRectBoundingBox = RectF( (result.boundingBox.left / scaleFactor) + diffWidth, (result.boundingBox.top / scaleFactor) + diffHeight, (result.boundingBox.right / scaleFactor) + diffWidth, (result.boundingBox.bottom / scaleFactor) + diffHeight ) val dotCenter = PointF( (actualRectBoundingBox.right + actualRectBoundingBox.left) / 2, (actualRectBoundingBox.bottom + actualRectBoundingBox.top) / 2, ) // Transform to new object to hold the data inside. // This object is necessary to avoid performance TransformedDetectionResult(actualRectBoundingBox, result.boundingBox, dotCenter) } Log.d( TAG, "srcImage: ${srcImage.width}/${srcImage.height} - imageView: ${width}/${height} => scaleFactor: $scaleFactor" ) // Invalid to re-draw the canvas // Method onDraw will be called with new data. invalidate() } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // Getting detection results and draw the dot view onto detected object. transformedResults.forEach { result -> // Draw Dot View canvas.drawCircle(result.dotCenter.x, result.dotCenter.y, CLICKABLE_RADIUS, dotPaint) } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { val touchX = event.x val touchY = event.y val index = transformedResults.indexOfFirst { val dx = (touchX - it.dotCenter.x).toDouble().pow(2.0) val dy = (touchY - it.dotCenter.y).toDouble().pow(2.0) (dx + dy) < CLICKABLE_RADIUS.toDouble().pow(2.0) } // If a matching object found, call the objectClickListener if (index != -1) { cropBitMapBasedResult(transformedResults[index])?.let { onObjectClickListener?.invoke(it) } } } } return super.onTouchEvent(event) } /** * This function will be used to crop the segment of Bitmap based touching by user. */ private fun cropBitMapBasedResult(result: TransformedDetectionResult): Bitmap? { // Crop image from Original Bitmap with Original Rect Bounding Box (drawable as? BitmapDrawable)?.bitmap?.let { return Bitmap.createBitmap( it, result.originalBoxRectF.left, result.originalBoxRectF.top, result.originalBoxRectF.width(), result.originalBoxRectF.height() ) } return null } /** * Return Dot Paint to draw circle */ private fun createDotPaint() = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE style = Paint.Style.FILL setShadowLayer(SHADOW_RADIUS, 0F, 0F, Color.BLACK) // Force to use software to render by disable hardware acceleration. // Important: the shadow will not work without this line. setLayerType(LAYER_TYPE_SOFTWARE, this) } } /** * This class holds the transformed data * @property: actualBoxRectF: The bounding box after calculated * @property: originalBoxRectF: The original bounding box (Before transformed), use for crop bitmap. */ data class TransformedDetectionResult( val actualBoxRectF: RectF, val originalBoxRectF: Rect, val dotCenter: PointF )
Count/app/src/androidTest/java/com/flagg/msu/count/ExampleInstrumentedTest.kt
878685069
package com.flagg.msu.count 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.flagg.msu.count", appContext.packageName) } }
Count/app/src/test/java/com/flagg/msu/count/ExampleUnitTest.kt
2100500925
package com.flagg.msu.count 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) } }
Count/app/src/main/java/com/flagg/msu/count/MainActivity.kt
3086545751
package com.flagg.msu.count import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class MainActivity: AppCompatActivity() { private lateinit var tap_button: Button private lateinit var tap_count: TextView private val count = Counter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) tap_button = findViewById(R.id.tap_button) tap_count = findViewById(R.id.tap_count) tap_button.setOnClickListener { count.addCount() tap_count.text = count.getCount().toString() } } class Counter { private var count: Int = 0 fun addCount() { count++ } fun getCount(): Int { return count } } }
Jetpack-Compose-Basics/app/src/androidTest/java/hr/foi/rampu/jetpackcomposebasics/ExampleInstrumentedTest.kt
2692772171
package hr.foi.rampu.jetpackcomposebasics 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("hr.foi.rampu.jetpackcomposebasics", appContext.packageName) } }
Jetpack-Compose-Basics/app/src/test/java/hr/foi/rampu/jetpackcomposebasics/ExampleUnitTest.kt
2031528875
package hr.foi.rampu.jetpackcomposebasics 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) } }
Jetpack-Compose-Basics/app/src/main/java/hr/foi/rampu/jetpackcomposebasics/ui/theme/Color.kt
3703088050
package hr.foi.rampu.jetpackcomposebasics.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 Navy = Color(0xFF073042) val Blue = Color(0xFF4285F4) val LightBlue = Color(0xFFD7EFFE) val Chartreuse = Color(0xFFEFF7CF)
Jetpack-Compose-Basics/app/src/main/java/hr/foi/rampu/jetpackcomposebasics/ui/theme/Theme.kt
2902194039
package hr.foi.rampu.jetpackcomposebasics.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.Color 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( surface = Blue, onSurface = Navy, primary = Navy, onPrimary = Chartreuse ) private val LightColorScheme = lightColorScheme( primary = LightBlue, surface = Blue, onSurface = Color.White, onPrimary = Navy /* 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 JetpackComposeBasicsTheme( 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 ) }
Jetpack-Compose-Basics/app/src/main/java/hr/foi/rampu/jetpackcomposebasics/ui/theme/Type.kt
3634125787
package hr.foi.rampu.jetpackcomposebasics.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 ) */ )
Jetpack-Compose-Basics/app/src/main/java/hr/foi/rampu/jetpackcomposebasics/MainActivity.kt
639741504
package hr.foi.rampu.jetpackcomposebasics import android.content.res.Configuration.UI_MODE_NIGHT_YES import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import hr.foi.rampu.jetpackcomposebasics.ui.theme.JetpackComposeBasicsTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { JetpackComposeBasicsTheme { MyApp(modifier = Modifier.fillMaxSize()) } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { var expanded by rememberSaveable { mutableStateOf(false) } Surface( color = MaterialTheme.colorScheme.primary, modifier = modifier.padding(vertical = 4.dp, horizontal = 8.dp) ){ Row(modifier = modifier .padding(12.dp) .animateContentSize( animationSpec = tween( durationMillis = 350, easing = FastOutSlowInEasing ) )){ Column( modifier = Modifier .weight(1f) .padding(12.dp) ) { Text(text = "Hello,") Text ( text = name, style = MaterialTheme.typography.headlineMedium.copy( fontWeight = FontWeight.ExtraBold ) ) if(expanded) { Text( text = ("Composem ipsum color sit lazy, " + "padding theme elit, sed do bouncy.").repeat(4) ) } } IconButton( onClick = { expanded = !expanded } ) { Icon( imageVector = if(expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, if (expanded) stringResource(R.string.show_less) else stringResource(R.string.show_more) ) } } } } @Composable fun Greetings( modifier: Modifier = Modifier, names: List<String> = List(30) {"$it"} ){ LazyColumn(modifier = modifier.padding(vertical = 4.dp)) { items(items = names){ name -> Greeting(name = name) } } } @Composable fun MyApp( modifier: Modifier = Modifier ){ Surface( modifier = modifier, color = MaterialTheme.colorScheme.background ) { var shouldShowOnboarding by rememberSaveable { mutableStateOf(true) } if(shouldShowOnboarding){ OnboardingScreen(onContinueClicked = { shouldShowOnboarding = false}) }else{ Greetings() } } } @Composable fun OnboardingScreen( onContinueClicked: () -> Unit, modifier: Modifier = Modifier ){ var shouldShowOnboarding by rememberSaveable { mutableStateOf(true) } Column( modifier = modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ){ Text("Welcome to the Basics Codelab") Button( modifier = Modifier.padding(vertical = 24.dp), onClick = onContinueClicked ) { Text(text = "Continue") } } } //@Preview( // showBackground = true, // widthDp = 320, // uiMode = UI_MODE_NIGHT_YES, // name = "GreetingsDarkPreview" //) @Preview(showBackground = true, widthDp = 320) @Composable fun GreetingPreview() { JetpackComposeBasicsTheme { Greetings() } } //@Preview(showBackground = true, widthDp = 320) //@Composable //fun OnBoardingPreview() { // JetpackComposeBasicsTheme { // OnboardingScreen(onContinueClicked = {}) // } //}
loginv4/app/src/androidTest/java/com/example/loginv4/ExampleInstrumentedTest.kt
582652026
package com.example.loginv4 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.loginv4", appContext.packageName) } }
loginv4/app/src/test/java/com/example/loginv4/ExampleUnitTest.kt
1977430916
package com.example.loginv4 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) } }
loginv4/app/src/main/java/com/example/loginv4/inicio.kt
2113770326
package com.example.loginv4 import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class inicio : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_inicio) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } } }
loginv4/app/src/main/java/com/example/loginv4/MainActivity.kt
158364182
package com.example.loginv4 import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast //import com.google.firebase.Firebase import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class MainActivity : AppCompatActivity() { private lateinit var firebaseAuth: FirebaseAuth private lateinit var auth: FirebaseAuth.AuthStateListener override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val btningresar: Button = findViewById(R.id.ButtonAccess) val btnadd: Button = findViewById(R.id.ButtonAdd) val emailtxt: TextView = findViewById(R.id.emailText) val passtxt: TextView = findViewById(R.id.passwortText) firebaseAuth = Firebase.auth btningresar.setOnClickListener() { if(emailtxt.text.isNotEmpty() && passtxt.text.isNotEmpty()){ singIn(emailtxt.text.toString(), passtxt.text.toString()) } else{ Toast.makeText(baseContext, "Error de email y/o contrasena esta en blanco", Toast.LENGTH_SHORT) .show() } } } private fun singIn(email: String, password: String) { firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this) { task -> if (task.isSuccessful) { val user = firebaseAuth.currentUser Toast.makeText(baseContext, user?.uid.toString(), Toast.LENGTH_SHORT).show() val i = Intent(this, inicio::class.java) startActivity(i) } else { Toast.makeText(baseContext, "Error de email y/o contrasena", Toast.LENGTH_SHORT) .show() } } } } /*Hola este es un comentario de prueba*/ //fun main (){ // print( "hola") // Write a message to the database //val database = Firebase.database // val myRef = database.getReference("message") // myRef.setValue("Hello, World!")
RandomuserMVVM/app/src/androidTest/java/io/github/christianfajardo/randomuser/ExampleInstrumentedTest.kt
355587428
package io.github.christianfajardo.randomuser 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.* @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("io.github.kabirnayeem99.friends", appContext.packageName) } }
RandomuserMVVM/app/src/test/java/io/github/christianfajardo/randomuser/viewmodels/UserViewModelTest.kt
2205400045
package io.github.christianfajardo.randomuser.viewmodels import junit.framework.TestCase class UserViewModelTest : TestCase() { public override fun setUp() { super.setUp() } }
RandomuserMVVM/app/src/test/java/io/github/christianfajardo/randomuser/ExampleUnitTest.kt
384086900
package io.github.christianfajardo.randomuser import org.junit.Test import org.junit.Assert.* class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/di/NetworkModule.kt
1758362025
package io.github.christianfajardo.randomuser.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import io.github.christianfajardo.randomuser.BuildConfig import io.github.christianfajardo.randomuser.data.sources.RemoteDataSource import io.github.christianfajardo.randomuser.utils.Constants.BASE_URL import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class NetworkModule { @Singleton @Provides fun providesHttpLoggingInterceptor(): HttpLoggingInterceptor { val levelType: HttpLoggingInterceptor.Level = if (BuildConfig.BUILD_TYPE.contentEquals("debug")) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE return HttpLoggingInterceptor() .apply { level = levelType } } @Singleton @Provides fun providesOkHttpClient( httpLoggingInterceptor: HttpLoggingInterceptor, ): OkHttpClient = OkHttpClient .Builder() .addInterceptor(httpLoggingInterceptor) .readTimeout(10L, TimeUnit.SECONDS) .writeTimeout(10L, TimeUnit.SECONDS) .build() @Singleton @Provides fun provideRxJavaCallAdapterFactory(): RxJava3CallAdapterFactory = RxJava3CallAdapterFactory.create() @Singleton @Provides fun provideGsonConverter(): GsonConverterFactory = GsonConverterFactory.create() @Singleton @Provides fun provideRetrofit( okHttpClient: OkHttpClient, rxAdapter: RxJava3CallAdapterFactory, gsonConverter: GsonConverterFactory ): Retrofit = Retrofit.Builder() .addConverterFactory(gsonConverter) .baseUrl(BASE_URL) .client(okHttpClient) .addCallAdapterFactory(rxAdapter) .build() @Singleton @Provides fun provideRemoteDataSource(retrofit: Retrofit): RemoteDataSource = retrofit.create(RemoteDataSource::class.java) }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/di/ViewModelModule.kt
1672959666
package io.github.christianfajardo.randomuser.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import io.github.christianfajardo.randomuser.data.repository.RandomUserRepositoryImpl import io.github.christianfajardo.randomuser.data.sources.RemoteDataSource import io.github.christianfajardo.randomuser.domain.repository.RandomUserRepository @Module @InstallIn(ViewModelComponent::class) class ViewModelModule { @Provides fun providesRepository(remoteDataSource: RemoteDataSource): RandomUserRepository = RandomUserRepositoryImpl(remoteDataSource) }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/di/ActivityModule.kt
3701125588
package io.github.christianfajardo.randomuser.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.ActivityComponent import io.github.christianfajardo.randomuser.presentation.landing.UserAdapter import io.reactivex.rxjava3.disposables.CompositeDisposable @Module @InstallIn(ActivityComponent::class) class ActivityModule { @Provides fun provideUserAdapter(): UserAdapter = UserAdapter() @Provides fun provideCompositeDisposable(): CompositeDisposable = CompositeDisposable() }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/RandomUser.kt
2475862699
package io.github.christianfajardo.randomuser import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class RandomUser : Application()
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/utils/UtilitiesExtensions.kt
428643878
package io.github.christianfajardo.randomuser.utils import android.util.Log import io.github.christianfajardo.randomuser.BuildConfig fun Exception.print(tag: String, functionName: String) { if (BuildConfig.DEBUG) { Log.e( tag, "$functionName: ${ this.message ?: "An unknown error has occurred" }", this ) } }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/utils/Resource.kt
1697901732
package io.github.christianfajardo.randomuser.utils /** * Generic Resource class * for more sophisticated status and * error handling * * This sealed class holds, three state, * * [Success], which takes the data as a parameter * * [Error], which takes error message [String] as a param * * [Loading], which takes no param * */ sealed class Resource<T>( val data: T? = null, val message: String? = null ) { /** * Signifies the successful state, * which may mean the data has been returned successfully * * takes the data (of [Any] type) as a parameter */ class Success<T>(data: T) : Resource<T>(data) /** * Signifies the error state, * which means the data could not be loaded, * but there has been provided an error message * to inform about the issue. * * takes the error message ([String]) as a parameter */ class Error<T>(message: String, data: T? = null) : Resource<T>(data, message) /** * Signifies the loading state, * which means the data is not loaded yet, * it is currently processing */ class Loading<T> : Resource<T>() }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/utils/NetworkUtilities.kt
1467656756
package io.github.christianfajardo.randomuser.utils import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers object NetworkUtilities { /** * Observers network status */ fun observerNetwork(): Observable<Boolean> { val command = "ping -c 1 example.com" return Observable.just(Runtime.getRuntime().exec(command).waitFor() == 0) .observeOn(Schedulers.io()) .onErrorReturn { false } } }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/utils/Constants.kt
3123623710
package io.github.christianfajardo.randomuser.utils /** * This class holds all the app level constants, * that won't change during the execution time of * this application */ object Constants { /** * Wi-Fi settings action name to open it directly with implicit intent */ const val WIFI_SETTING_ACTION: String = "android.settings.WIFI_SETTINGS" /** * The base API URL to fetch the data from */ const val BASE_URL: String = "https://randomuser.me/api/" }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/data/repository/RandomUserRepositoryImpl.kt
2892691585
package io.github.christianfajardo.randomuser.data.repository import io.github.christianfajardo.randomuser.data.sources.RemoteDataSource import io.github.christianfajardo.randomuser.domain.model.User import io.github.christianfajardo.randomuser.domain.repository.RandomUserRepository import io.github.christianfajardo.randomuser.utils.Resource import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.schedulers.Schedulers import javax.inject.Inject class RandomUserRepositoryImpl @Inject constructor(private var remoteDataSource: RemoteDataSource) : RandomUserRepository { override fun getUserList(): Flowable<Resource<List<User>>> { return remoteDataSource.getResponse() .retry(3) .observeOn(Schedulers.io()) .map { apiResponse -> Resource.Success(apiResponse.userList) as Resource<List<User>> } .onErrorReturnItem(Resource.Error("An error has occurred")) } }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/data/sources/RemoteDataSource.kt
4045051488
package io.github.christianfajardo.randomuser.data.sources import io.github.christianfajardo.randomuser.domain.model.ApiResponse import io.reactivex.rxjava3.core.Flowable import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface RemoteDataSource { @GET(".") fun getResponse( @Query("results") resultAmount: Int = 100 ): Flowable<ApiResponse> }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/repository/RandomUserRepository.kt
2724882404
package io.github.christianfajardo.randomuser.domain.repository import io.github.christianfajardo.randomuser.domain.model.User import io.github.christianfajardo.randomuser.utils.Resource import io.reactivex.rxjava3.core.Flowable interface RandomUserRepository { fun getUserList(): Flowable<Resource<List<User>>> }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/Registered.kt
3885424061
package io.github.christianfajardo.randomuser.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class Registered( @SerializedName("date") val date: String, @SerializedName("age") val age: Int, ) : Parcelable
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/Location.kt
4134931949
package io.github.christianfajardo.randomuser.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class Location( @SerializedName("street") val street: Street, @SerializedName("city") val city: String, @SerializedName("state") val state: String, @SerializedName("country") val country: String, @SerializedName("postcode") val postcode: String, @SerializedName("coordinates") val coordinates: Coordinates, @SerializedName("timezone") val timezone: Timezone ) : Parcelable
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/Coordinates.kt
833607798
package io.github.christianfajardo.randomuser.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class Coordinates( @SerializedName("latitude") val latitude: String, @SerializedName("longitude") val longitude: String, ) : Parcelable
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/Timezone.kt
4077538041
package io.github.christianfajardo.randomuser.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class Timezone( @SerializedName("offset") val offset: String, @SerializedName("description") val description: String ) : Parcelable
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/Name.kt
2957080467
package io.github.christianfajardo.randomuser.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class Name( @SerializedName("title") val title: String, @SerializedName("first") val first: String, @SerializedName("last") val last: String ) : Parcelable
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/Picture.kt
2206539080
package io.github.christianfajardo.randomuser.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class Picture( @SerializedName("large") val large: String, @SerializedName("medium") val medium: String, @SerializedName("thumbnail") val thumbnail: String ) : Parcelable
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/User.kt
66478133
package io.github.christianfajardo.randomuser.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class User( @SerializedName("name") val name: Name, @SerializedName("gender") val gender: String, @SerializedName("location") val location: Location, @SerializedName("email") val email: String, @SerializedName("phone") val phone: String, @SerializedName("cell") val cell: String, @SerializedName("picture") val picture: Picture, @SerializedName("registered") val registered: Registered, @SerializedName("coordinates") val coordinates: Coordinates? ) : Parcelable
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/Street.kt
1187572063
package io.github.christianfajardo.randomuser.domain.model import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.parcelize.Parcelize @Parcelize data class Street( @SerializedName("number") val number: Int, @SerializedName("name") val name: String ) : Parcelable
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/domain/model/ApiResponse.kt
3636476085
package io.github.christianfajardo.randomuser.domain.model import com.google.gson.annotations.SerializedName data class ApiResponse( @SerializedName("results") val userList: List<User> )
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/presentation/landing/UserViewModel.kt
4072398229
package io.github.christianfajardo.randomuser.presentation.landing import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import io.github.christianfajardo.randomuser.domain.model.User import io.github.christianfajardo.randomuser.domain.repository.RandomUserRepository import io.github.christianfajardo.randomuser.utils.NetworkUtilities import io.github.christianfajardo.randomuser.utils.Resource import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.schedulers.Schedulers import javax.inject.Inject @HiltViewModel class UserViewModel @Inject constructor(private var repo: RandomUserRepository) : ViewModel() { private var userListFlowablePrivate: Flowable<Resource<List<User>>> = repo.getUserList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .cache() fun getUsers(){ userListFlowablePrivate=repo.getUserList() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .cache() } private var internetStatusPrivate: Observable<Boolean> = NetworkUtilities .observerNetwork() .observeOn(AndroidSchedulers.mainThread()) var userListFlowable: Flowable<Resource<List<User>>> = userListFlowablePrivate var internetStatus: Observable<Boolean> = internetStatusPrivate }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/presentation/landing/UserAdapter.kt
3489564623
package io.github.christianfajardo.randomuser.presentation.landing import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.AsyncListDiffer import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.google.android.material.card.MaterialCardView import de.hdodenhof.circleimageview.CircleImageView import io.github.christianfajardo.randomuser.R import io.github.christianfajardo.randomuser.domain.model.User import io.github.christianfajardo.randomuser.presentation.userdetails.UserDetailsActivity import io.github.christianfajardo.randomuser.presentation.userdetails.UserDetailsActivity.Companion.USER_DATA import io.github.christianfajardo.randomuser.presentation.loadImage import javax.inject.Inject class UserAdapter @Inject constructor() : RecyclerView.Adapter<UserAdapter.UserViewHolder>() { inner class UserViewHolder(private var view: View) : RecyclerView.ViewHolder(view) { private val context: Context = view.context private var tvFullName: TextView = view.findViewById(R.id.tvFullName) private var tvCountry: TextView = view.findViewById(R.id.tvCountry) private var ivPortrait: CircleImageView = view.findViewById(R.id.ivPortrait) private var mcvUserCard: MaterialCardView = view.findViewById(R.id.mcvUserCard) @SuppressLint("SetTextI18n") fun bindTo(user: User) { tvFullName.text = "${user.name.first} ${user.name.last}" tvCountry.text = user.email ivPortrait.loadImage(user.picture.medium) mcvUserCard.setOnClickListener { val intent = Intent(view.context, UserDetailsActivity::class.java) intent.putExtra(USER_DATA, user) context.startActivity(intent) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder { val context = parent.context val inflater = LayoutInflater.from(context) val userCard = inflater.inflate(R.layout.list_item_user, parent, false) return UserViewHolder(userCard) } override fun onBindViewHolder(holder: UserViewHolder, position: Int) { val user = differ.currentList[position] holder.bindTo(user) } fun getList ()=differ.currentList override fun getItemCount(): Int = differ.currentList.size private val diffCallback = object : DiffUtil.ItemCallback<User>() { override fun areItemsTheSame(oldItem: User, newItem: User): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: User, newItem: User): Boolean { if (oldItem.location.country != newItem.location.country) { return false } if (oldItem.name.first != newItem.name.first) { return false } if (oldItem.name.last != newItem.name.last) { return false } if (oldItem.picture.medium != newItem.picture.medium) { return false } return true } } val differ = AsyncListDiffer(this, diffCallback) }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/presentation/landing/LandingActivity.kt
922914576
package io.github.christianfajardo.randomuser.presentation.landing import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.util.Log import android.view.View import android.widget.ImageView import android.widget.ProgressBar import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.SearchView import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import io.github.christianfajardo.randomuser.BuildConfig import io.github.christianfajardo.randomuser.utils.Resource import io.github.christianfajardo.randomuser.utils.Constants import io.github.christianfajardo.randomuser.utils.print import io.github.christianfajardo.randomuser.R import io.reactivex.rxjava3.disposables.CompositeDisposable import javax.inject.Inject @AndroidEntryPoint class LandingActivity : AppCompatActivity() { private lateinit var rvFriends: RecyclerView private lateinit var pbLoading: ProgressBar private lateinit var ivNoInternet: ImageView private lateinit var parentLayout: View private lateinit var searchView: SearchView @Inject lateinit var compositeDisposable: CompositeDisposable @Inject lateinit var userAdapter: UserAdapter private val userViewModel: UserViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_landing) initViews() observeViewModel() setUpRecyclerView() setupSearchView() } private fun setupSearchView() { searchView = findViewById(R.id.searchView) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return false } override fun onQueryTextChange(newText: String?): Boolean { if (newText.isNullOrBlank()) { userViewModel.getUsers() compositeDisposable.add( userViewModel.userListFlowable.subscribe { resource -> when (resource) { is Resource.Success -> { userAdapter.differ.submitList(resource.data) } } } ) return true } rvFriends.visibility = View.VISIBLE val userAdapterList = userAdapter.getList() val filteredList = if (!newText.isNullOrBlank()) { val list=userAdapterList.filter { user -> val fullName = "${user.name.first} ${user.name.last}" fullName.contains(newText, ignoreCase = true) || user.email.contains(newText, ignoreCase = true) } list } else { Log.d("No","No action") emptyList() } userAdapter.differ.submitList(filteredList) return true } }) } private fun initViews() { parentLayout = findViewById(android.R.id.content) rvFriends = findViewById(R.id.rvFriends) pbLoading = findViewById(R.id.pbLoading) ivNoInternet = findViewById(R.id.ivNoInternet) } private fun observeViewModel() { compositeDisposable.add( userViewModel .userListFlowable .subscribe { resource -> when (resource) { is Resource.Loading -> { pbLoading.visibility = View.VISIBLE ivNoInternet.visibility = View.GONE } is Resource.Error -> { pbLoading.visibility = View.GONE ivNoInternet.visibility = View.VISIBLE if (BuildConfig.DEBUG) { Log.e(tag, "setUpObserver: ${resource.message}") } showErrorSnackBar() } is Resource.Success -> { pbLoading.visibility = View.GONE ivNoInternet.visibility = View.GONE rvFriends.visibility = View.VISIBLE userAdapter.differ.submitList(resource.data) } } }) } override fun onStop() { compositeDisposable.clear() super.onStop() } private fun showErrorSnackBar() { val snackBar = Snackbar.make(parentLayout, "Something went wrong", Snackbar.LENGTH_SHORT) compositeDisposable.add(userViewModel.internetStatus.subscribe { internetStatus -> if (!internetStatus) { snackBar.setText("Your Internet Connection is off") snackBar.setAction( "TURN ON" ) { try { launchWifiSettings() userViewModel.userListFlowable.retry() } catch (e: Exception) { e.print(tag, "launchwifi set") snackBar.setText("Could not open Wi-Fi settings") snackBar.show() } } snackBar.show() } else { snackBar.show() } }) } private fun setUpRecyclerView() { rvFriends.apply { val gridViewItemAmount: Int = 3 layoutManager = if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) { GridLayoutManager( this@LandingActivity, gridViewItemAmount ) } else { LinearLayoutManager(this@LandingActivity) } adapter = userAdapter overScrollMode = View.OVER_SCROLL_NEVER } } private fun launchWifiSettings() { val intent = Intent(Constants.WIFI_SETTING_ACTION) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) } private val tag = "LandingActivity" }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/presentation/userdetails/UserDetailsActivity.kt
3134121401
package io.github.christianfajardo.randomuser.presentation.userdetails import android.annotation.SuppressLint import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import io.github.christianfajardo.randomuser.domain.model.User import android.content.Intent import android.net.Uri import android.widget.Toast import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.google.android.material.card.MaterialCardView import dagger.hilt.android.AndroidEntryPoint import io.github.christianfajardo.randomuser.R import io.github.christianfajardo.randomuser.presentation.loadImage import java.text.SimpleDateFormat import java.util.Locale @AndroidEntryPoint class UserDetailsActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var ivPortraitDetails: ImageView private lateinit var tvFullNameDetails: TextView private lateinit var tvAddressDetails: TextView private lateinit var tvCityDetails: TextView private lateinit var tvEmailDetails: TextView private lateinit var tvCellPhoneDetails: TextView private lateinit var llEmail: LinearLayout private lateinit var mcvUserCard: MaterialCardView private lateinit var tvGenderDetails: TextView private lateinit var tvRegisteredDetails: TextView private lateinit var tvCoordinatesDetails: TextView private lateinit var map: GoogleMap override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user_details) initViews() showUpButton() getUserData() val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } // shows the back button in the action bar private fun showUpButton() { supportActionBar?.setDisplayHomeAsUpEnabled(true) } // change the navigate up functionality to the onBackPressed // so that, the activity in the back stack gets loaded override fun onSupportNavigateUp(): Boolean { super.onBackPressed() return false } private fun initViews() { ivPortraitDetails = findViewById(R.id.ivPortrait) tvFullNameDetails = findViewById(R.id.tvFullNameDetails) tvAddressDetails = findViewById(R.id.tvAddressDetails) tvCityDetails = findViewById(R.id.tvCityDetails) tvEmailDetails = findViewById(R.id.tvEmailDetails) tvCellPhoneDetails = findViewById(R.id.tvCellPhoneDetails) llEmail = findViewById(R.id.llEmail) mcvUserCard = findViewById(R.id.mcvUserCard) tvGenderDetails= findViewById(R.id.tvGenderDetails) tvRegisteredDetails=findViewById(R.id.tvRegisteredDetails) tvCoordinatesDetails=findViewById(R.id.tvCoordinatesDetails) } // gets the user data sent by the previous intent // and loads the UI if the user data can be retrieved private fun getUserData() { val userData = intent.getParcelableExtra<User>(USER_DATA) if (userData != null) { loadUi(userData) } else { Toast.makeText(this, "User details could not be retrieved.", Toast.LENGTH_SHORT).show() } } @SuppressLint("SetTextI18n") private fun loadUi(user: User) { ivPortraitDetails.loadImage(user.picture.large) tvFullNameDetails.text = "${user.name.first} ${user.name.last}" tvAddressDetails.text = user.location.street.name tvCityDetails.text = "${user.location.city}, ${user.location.state}, ${user.location.country}" tvEmailDetails.text = user.email tvCellPhoneDetails.text = user.cell tvGenderDetails.text= user.gender val registrationDateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault()) val registrationDate = registrationDateFormat.parse(user.registered.date) val formattedRegistrationDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) .format(registrationDate) tvRegisteredDetails.text = formattedRegistrationDate tvCoordinatesDetails.text= "${user.location.coordinates.latitude} ${user.location.coordinates.longitude}" llEmail.setOnClickListener { navigateToEmail(user.email) } // sets the action bar title to the first name of the user supportActionBar?.subtitle = "${user.name.first} ${user.name.last}" } // launch email app to send an mail to the user's mail private fun navigateToEmail(email: String) { val emailIntent = Intent(Intent.ACTION_SENDTO).apply { data = Uri.parse("mailto:$email") } startActivity(Intent.createChooser(emailIntent, "Send email")) } override fun onMapReady(googleMap: GoogleMap) { map = googleMap val coordinates = intent.getParcelableExtra<User>(USER_DATA)?.location?.coordinates if (coordinates != null) { val location = LatLng(coordinates.latitude.toDouble(), coordinates.longitude.toDouble()) map.addMarker(MarkerOptions().position(location).title("User's Location")) map.moveCamera(CameraUpdateFactory.newLatLng(location)) map.animateCamera(CameraUpdateFactory.zoomTo(10.0f)) } } companion object { const val USER_DATA = "user_data" } }
RandomuserMVVM/app/src/main/java/io/github/christianfajardo/randomuser/presentation/PresentationExtensions.kt
2454071054
package io.github.christianfajardo.randomuser.presentation import android.widget.ImageView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import io.github.christianfajardo.randomuser.R fun ImageView.loadImage(url: String?) { val options = RequestOptions() .error(R.drawable.ic_image_not_found) .placeholder(R.drawable.ic_image_downloading) Glide.with(this.context) .setDefaultRequestOptions(options) .load(url) .into(this) }
Logren/app/src/androidTest/java/com/ozcanbayram/logren/ExampleInstrumentedTest.kt
63710884
package com.ozcanbayram.logren 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.ozcanbayram.logren", appContext.packageName) } }
Logren/app/src/test/java/com/ozcanbayram/logren/ExampleUnitTest.kt
3868841980
package com.ozcanbayram.logren 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) } }
Logren/app/src/main/java/com/ozcanbayram/logren/Details.kt
626148930
package com.ozcanbayram.logren import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.ozcanbayram.logren.databinding.ActivityDetailsBinding import com.ozcanbayram.logren.databinding.ActivityLoginBinding class Details : AppCompatActivity() { private lateinit var binding : ActivityDetailsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityDetailsBinding.inflate(layoutInflater) val view = binding.root setContentView(view) val intent = intent val term = intent.getStringExtra("term") val explanation = intent.getStringExtra("explanation") binding.header.text = term binding.explanation.text = explanation } }
Logren/app/src/main/java/com/ozcanbayram/logren/adapter/TermsAdapter.kt
2455277767
package com.ozcanbayram.logren.adapter import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.ozcanbayram.logren.Details import com.ozcanbayram.logren.databinding.RecyclerRowBinding import com.ozcanbayram.logren.model.Term class TermsAdapter(private val termList : ArrayList<Term>) : RecyclerView.Adapter<TermsAdapter.TermsViewHolder>() { class TermsViewHolder(val binding : RecyclerRowBinding) : RecyclerView.ViewHolder(binding.root){ } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TermsViewHolder { val binding =RecyclerRowBinding.inflate(LayoutInflater.from(parent.context),parent,false) return TermsViewHolder(binding) } override fun getItemCount(): Int { return termList.size } override fun onBindViewHolder(holder: TermsViewHolder, position: Int) { holder.binding.termName.text =termList.get(position).term holder.binding.recyclerRow.setOnClickListener { val intent = Intent(holder.itemView.context, Details::class.java) intent.putExtra("term",termList.get(position).term) intent.putExtra("explanation",termList.get(position).explanation) holder.itemView.context.startActivity(intent) } } }
Logren/app/src/main/java/com/ozcanbayram/logren/model/Term.kt
737079388
package com.ozcanbayram.logren.model data class Term(val term : String, val explanation : String) { }
Logren/app/src/main/java/com/ozcanbayram/logren/view/ActivityRegsiter.kt
2448530771
package com.ozcanbayram.logren.view import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.ozcanbayram.logren.databinding.ActivityRegsiterBinding class ActivityRegsiter : AppCompatActivity() { private lateinit var binding : ActivityRegsiterBinding //For Firebase private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRegsiterBinding.inflate(layoutInflater) val view = binding.root setContentView(view) // Initialize Firebase Auth auth = Firebase.auth } fun register(view : View){ val email = binding.email.text.toString() val password = binding.password.text.toString() if(email.isEmpty() || password.isEmpty()){ Toast.makeText(this@ActivityRegsiter,"Lütfen E-Posta ve Parolanızı eksiksiz giriniz.",Toast.LENGTH_LONG).show() }else { auth.createUserWithEmailAndPassword(email,password).addOnSuccessListener { authResult -> val newuser =authResult.user Toast.makeText(this@ActivityRegsiter,"Kayıt Başarılı. Giriş Yapabilirsiniz.",Toast.LENGTH_LONG).show() val intent = Intent(this@ActivityRegsiter, LoginActivity::class.java) startActivity(intent) }.addOnFailureListener { Toast.makeText(this@ActivityRegsiter, it.localizedMessage, Toast.LENGTH_LONG).show() } } } }
Logren/app/src/main/java/com/ozcanbayram/logren/view/MainActivity.kt
1049085810
package com.ozcanbayram.logren.view import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.Query import com.google.firebase.firestore.firestore import com.ozcanbayram.logren.R import com.ozcanbayram.logren.adapter.TermsAdapter import com.ozcanbayram.logren.databinding.ActivityMainBinding import com.ozcanbayram.logren.model.Term import kotlin.collections.ArrayList class MainActivity : AppCompatActivity() { private lateinit var binding : ActivityMainBinding private lateinit var auth: FirebaseAuth private lateinit var db : FirebaseFirestore private lateinit var termArrayList : ArrayList<Term> private lateinit var termsAdapter : TermsAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) // Initialize Firebase Auth auth = Firebase.auth db = Firebase.firestore termArrayList = ArrayList<Term>() getData() binding.recyclerView.layoutManager = LinearLayoutManager(this) termsAdapter = TermsAdapter(termArrayList) binding.recyclerView.adapter = termsAdapter } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val menuInflater = menuInflater menuInflater.inflate(R.menu.main_menu,menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if(item.itemId == R.id.log_out){ auth.signOut() val intent = Intent(this, Welcome::class.java) startActivity(intent) finish() } return super.onOptionsItemSelected(item) } private fun getData(){ db.collection("Terms").orderBy("term", Query.Direction.ASCENDING).addSnapshotListener { value, error -> if(error != null){ Toast.makeText(this@MainActivity,error.localizedMessage,Toast.LENGTH_LONG).show() }else{ if(value != null){ if(!value.isEmpty){ val documents = value.documents for (document in documents){ val term = document.get("term") as String val explanation = document.get("explanation") as String val terms = Term(term, explanation ) termArrayList.add(terms) } termsAdapter.notifyDataSetChanged() } } } } } }
Logren/app/src/main/java/com/ozcanbayram/logren/view/Welcome.kt
2006710460
package com.ozcanbayram.logren.view import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth import com.ozcanbayram.logren.databinding.ActivityWelcomeBinding class Welcome : AppCompatActivity() { private lateinit var binding : ActivityWelcomeBinding private lateinit var auth : FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityWelcomeBinding.inflate(layoutInflater) val view = binding.root setContentView(view) binding.registerButton.setOnClickListener { val intent = Intent(this@Welcome, ActivityRegsiter::class.java) startActivity(intent) } binding.loginButton.setOnClickListener { val intent = Intent(this@Welcome, LoginActivity::class.java) startActivity(intent) } auth = Firebase.auth val currentUSer = auth.currentUser //Hatırlama kontrolü -> if(currentUSer != null){ val intent = Intent(this@Welcome,MainActivity::class.java) startActivity(intent) finish() } } private fun register(view : View){ } private fun login(view : View){ } }
Logren/app/src/main/java/com/ozcanbayram/logren/view/LoginActivity.kt
2121021287
package com.ozcanbayram.logren.view import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import com.ozcanbayram.logren.databinding.ActivityLoginBinding import com.google.firebase.Firebase import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.auth class LoginActivity : AppCompatActivity() { private lateinit var binding : ActivityLoginBinding private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) val view = binding.root setContentView(view) // Initialize Firebase Auth auth = Firebase.auth } fun login(view : View){ val email = binding.editTextText.text.toString() val password = binding.editTextTextPassword2.text.toString() if(email.equals("")||password.equals("")){ Toast.makeText(this,"Lütfen E-posta ve Şifre bilgilerinizi giriniz.", Toast.LENGTH_LONG).show() }else{ auth.signInWithEmailAndPassword(email,password).addOnSuccessListener { val intent = Intent(this@LoginActivity, MainActivity::class.java) Toast.makeText(this@LoginActivity,"Giriş başarılı.", Toast.LENGTH_SHORT).show() startActivity(intent) finish() }.addOnFailureListener { Toast.makeText(this@LoginActivity,it.localizedMessage, Toast.LENGTH_SHORT).show() } } } }
AndroidLearning/compose-training-unscramble/app/src/test/java/com/example/unscramble/ui/test/GameViewModelTest.kt
3765142397
package com.example.unscramble.ui.test import com.example.unscramble.data.MAX_NO_OF_WORDS import com.example.unscramble.data.SCORE_INCREASE import com.example.unscramble.data.getUnscrambledWord import com.example.unscramble.ui.GameViewModel import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertFalse import junit.framework.TestCase.assertTrue import org.junit.Assert.assertNotEquals import org.junit.Test class GameViewModelTest { private val viewModel = GameViewModel() @Test fun gameViewModel_CorrectWordGuessed_ScoreUpdatedAndErrorFlagUnset() { var currentGameUiState = viewModel.uiState.value val correctPlayerWord = getUnscrambledWord(currentGameUiState.currentScrambledWord) viewModel.updateUserGuess(correctPlayerWord) viewModel.checkUserGuess() currentGameUiState = viewModel.uiState.value assertFalse(currentGameUiState.isGuessedWordWrong) assertEquals(20, currentGameUiState.score) } companion object { private const val SCORE_AFTER_FIRST_CORRECT_ANSWER = SCORE_INCREASE } @Test fun gameViewModel_IncorrectGuess_ErrorFlagSet() { val incorrectPlayerWord = "and" viewModel.updateUserGuess(incorrectPlayerWord) viewModel.checkUserGuess() val currentGameUiState = viewModel.uiState.value //Assert that score is unchanged assertEquals(0, currentGameUiState.score) assertTrue(currentGameUiState.isGuessedWordWrong) } @Test fun gameViewModel_Initialization_FirstWordLoaded() { val gameUiState = viewModel.uiState.value val unScrambledWord = getUnscrambledWord(gameUiState.currentScrambledWord) //Assert that currnet word is scrambled assertNotEquals(unScrambledWord, gameUiState.currentScrambledWord) // Assert that current word count is set to 1. assertTrue(gameUiState.currentWordCount == 1) // Assert that initially the score is 0. assertTrue(gameUiState.score == 0) // Assert that the wrong word guessed is false. assertFalse(gameUiState.isGuessedWordWrong) // Assert that game is not over. assertFalse(gameUiState.isGameOver) } @Test fun gameViewModel_AllWordsGuessed_UiStateUpdatedCorrectly() { var expectedScore = 0 var currentGameUiState = viewModel.uiState.value var correctPlayerWord = getUnscrambledWord(currentGameUiState.currentScrambledWord) repeat(MAX_NO_OF_WORDS) { expectedScore += SCORE_INCREASE viewModel.updateUserGuess(correctPlayerWord) viewModel.checkUserGuess() currentGameUiState = viewModel.uiState.value correctPlayerWord = getUnscrambledWord(currentGameUiState.currentScrambledWord) assertEquals(expectedScore, currentGameUiState.score) } assertEquals(MAX_NO_OF_WORDS, currentGameUiState.currentWordCount) assertTrue(currentGameUiState.isGameOver) } }
AndroidLearning/compose-training-unscramble/app/src/test/java/com/example/unscramble/data/WordsData.kt
3865389887
/* * Copyright (c)2023 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.example.unscramble.data const val MAX_NO_OF_WORDS = 10 const val SCORE_INCREASE = 20 // List with all the words for the Game val allWords: Set<String> = setOf( "at", "sea", "home", "arise", "banana", "android", "birthday", "briefcase", "motorcycle", "cauliflower" ) /** * Maps words to their lengths. Each word in allWords has a unique length. This is required since * the words are randomly picked inside GameViewModel and the selection is unpredictable. */ private val wordLengthMap: Map<Int, String> = allWords.associateBy({ it.length }, { it }) internal fun getUnscrambledWord(scrambledWord: String) = wordLengthMap[scrambledWord.length] ?: ""
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/ui/GameUiState.kt
3219515172
package com.example.unscramble.ui data class GameUiState( val currentScrambledWord: String = "", val isGuessedWordWrong: Boolean = false, val currentWordCount: Int = 1, val score: Int = 0, val isGameOver: Boolean = false )
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/ui/GameScreen.kt
4224056311
/* * Copyright (C) 2023 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.example.unscramble.ui import android.app.Activity import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.MaterialTheme.shapes import androidx.compose.material3.MaterialTheme.typography import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.TextFieldDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.unscramble.R import com.example.unscramble.ui.theme.UnscrambleTheme @Composable fun GameScreen( gameViewModel: GameViewModel = viewModel() ) { val gameUiState by gameViewModel.uiState.collectAsState() val mediumPadding = dimensionResource(R.dimen.padding_medium) if (gameUiState.isGameOver) { FinalScoreDialog(score = gameUiState.score, onPlayAgain = { gameViewModel.resetGame() }) } Column( modifier = Modifier .statusBarsPadding() .verticalScroll(rememberScrollState()) .safeDrawingPadding() .padding(mediumPadding), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(R.string.app_name), style = typography.titleLarge, ) GameLayout( onUserGuessChanged = { gameViewModel.updateUserGuess(it) }, userGuess = gameViewModel.userGuess, onKeyboardDone = { gameViewModel.checkUserGuess() }, currentScrambledWord = gameUiState.currentScrambledWord, isGuessWrong = gameUiState.isGuessedWordWrong, wordCount = gameUiState.currentWordCount, modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(mediumPadding) ) Column( modifier = Modifier .fillMaxWidth() .padding(mediumPadding), verticalArrangement = Arrangement.spacedBy(mediumPadding), horizontalAlignment = Alignment.CenterHorizontally ) { Button( modifier = Modifier.fillMaxWidth(), onClick = { gameViewModel.checkUserGuess() } ) { Text( text = stringResource(R.string.submit), fontSize = 16.sp ) } OutlinedButton( onClick = { gameViewModel.skipWord() }, modifier = Modifier.fillMaxWidth() ) { Text( text = stringResource(R.string.skip), fontSize = 16.sp ) } } GameStatus(score = gameUiState.score, modifier = Modifier.padding(20.dp)) } } @Composable fun GameStatus(score: Int, modifier: Modifier = Modifier) { Card( modifier = modifier ) { Text( text = stringResource(R.string.score, score), style = typography.headlineMedium, modifier = Modifier.padding(8.dp) ) } } @Composable fun GameLayout( onUserGuessChanged: (String) -> Unit, onKeyboardDone: () -> Unit, userGuess: String, currentScrambledWord: String, isGuessWrong: Boolean, wordCount: Int, modifier: Modifier = Modifier ) { val mediumPadding = dimensionResource(R.dimen.padding_medium) Card( modifier = modifier, elevation = CardDefaults.cardElevation(defaultElevation = 5.dp) ) { Column( verticalArrangement = Arrangement.spacedBy(mediumPadding), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(mediumPadding) ) { Text( modifier = Modifier .clip(shapes.medium) .background(colorScheme.surfaceTint) .padding(horizontal = 10.dp, vertical = 4.dp) .align(alignment = Alignment.End), text = stringResource(R.string.word_count, wordCount), style = typography.titleMedium, color = colorScheme.onPrimary ) Text( text = currentScrambledWord, fontSize = 45.sp, modifier = Modifier.align(Alignment.CenterHorizontally), style = typography.displayMedium ) Text( text = stringResource(R.string.instructions), textAlign = TextAlign.Center, style = typography.titleMedium ) OutlinedTextField( value = userGuess, singleLine = true, shape = shapes.large, modifier = Modifier.fillMaxWidth(), colors = TextFieldDefaults.colors( focusedContainerColor = colorScheme.surface, unfocusedContainerColor = colorScheme.surface, disabledContainerColor = colorScheme.surface, ), onValueChange = { onUserGuessChanged(it) }, label = { if (isGuessWrong) Text(stringResource(R.string.enter_your_word)) else Text( text = stringResource( id = R.string.enter_your_word ) ) }, isError = isGuessWrong, keyboardOptions = KeyboardOptions.Default.copy( imeAction = ImeAction.Done ), keyboardActions = KeyboardActions( onDone = { onKeyboardDone() } ) ) } } } /* * Creates and shows an AlertDialog with final score. */ @Composable private fun FinalScoreDialog( score: Int, onPlayAgain: () -> Unit, modifier: Modifier = Modifier ) { val activity = (LocalContext.current as Activity) AlertDialog( onDismissRequest = { // Dismiss the dialog when the user clicks outside the dialog or on the back // button. If you want to disable that functionality, simply use an empty // onCloseRequest. }, title = { Text(text = stringResource(R.string.congratulations)) }, text = { Text(text = stringResource(R.string.you_scored, score)) }, modifier = modifier, dismissButton = { TextButton( onClick = { activity.finish() } ) { Text(text = stringResource(R.string.exit)) } }, confirmButton = { TextButton(onClick = onPlayAgain) { Text(text = stringResource(R.string.play_again)) } } ) } @Preview(showBackground = true) @Composable fun GameScreenPreview() { UnscrambleTheme { GameScreen() } }
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/ui/GameViewModel.kt
891328432
package com.example.unscramble.ui import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import com.example.unscramble.data.MAX_NO_OF_WORDS import com.example.unscramble.data.SCORE_INCREASE import com.example.unscramble.data.allWords import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update class GameViewModel : ViewModel() { private val _uiState = MutableStateFlow(GameUiState()) val uiState: StateFlow<GameUiState> = _uiState.asStateFlow() private lateinit var currentWord: String var userGuess by mutableStateOf("") private set // Set of words used in the game private var usedWords: MutableSet<String> = mutableSetOf() fun pickRandomWordAndShuffle(): String { currentWord = allWords.random() if (usedWords.contains(currentWord)) { return pickRandomWordAndShuffle() } else { usedWords.add(currentWord) return shuffleCurrentWord(currentWord) } } private fun shuffleCurrentWord(currentWord: String): String { val tempWord = currentWord.toCharArray() tempWord.shuffle() while (String(tempWord).equals(currentWord)) { tempWord.shuffle() } return String(tempWord) } init { resetGame() } fun resetGame(): Unit { usedWords.clear() _uiState.value = GameUiState(currentScrambledWord = pickRandomWordAndShuffle()) } fun updateUserGuess(guessedWord: String) { userGuess = guessedWord } fun checkUserGuess() { if (userGuess.equals(currentWord, ignoreCase = true)) { val updatedScore = _uiState.value.score.plus(SCORE_INCREASE) updateGameState(updatedScore) } else { _uiState.update { currentState -> currentState.copy(isGuessedWordWrong = true) } } updateUserGuess("") } private fun updateGameState(score: Int) { if (usedWords.size == MAX_NO_OF_WORDS) { _uiState.update { it.copy( isGuessedWordWrong = false, score = score, isGameOver = true ) } } else { _uiState.update { it.copy( isGuessedWordWrong = false, currentScrambledWord = pickRandomWordAndShuffle(), score = score, currentWordCount = it.currentWordCount.inc() ) } } } fun skipWord() { updateGameState(_uiState.value.score) updateUserGuess("") } }
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/ui/theme/Shape.kt
1489455470
/* * Copyright (C) 2023 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.example.unscramble.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(10.dp), large = RoundedCornerShape(16.dp) )
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/ui/theme/Color.kt
2466800881
/* * Copyright (C) 2023 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.example.unscramble.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF4355B9) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFDEE0FF) val md_theme_light_onPrimaryContainer = Color(0xFF00105C) val md_theme_light_secondary = Color(0xFF5B5D72) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFE0E1F9) val md_theme_light_onSecondaryContainer = Color(0xFF181A2C) val md_theme_light_tertiary = Color(0xFF77536D) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFFFD7F1) val md_theme_light_onTertiaryContainer = Color(0xFF2D1228) 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(0xFFFEFBFF) val md_theme_light_onBackground = Color(0xFF1B1B1F) val md_theme_light_surface = Color(0xFFFEFBFF) val md_theme_light_onSurface = Color(0xFF1B1B1F) val md_theme_light_surfaceVariant = Color(0xFFE3E1EC) val md_theme_light_onSurfaceVariant = Color(0xFF46464F) val md_theme_light_outline = Color(0xFF767680) val md_theme_light_inverseOnSurface = Color(0xFFF3F0F4) val md_theme_light_inverseSurface = Color(0xFF303034) val md_theme_light_inversePrimary = Color(0xFFBAC3FF) val md_theme_light_surfaceTint = Color(0xFF4355B9) val md_theme_light_outlineVariant = Color(0xFFC7C5D0) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFBAC3FF) val md_theme_dark_onPrimary = Color(0xFF08218A) val md_theme_dark_primaryContainer = Color(0xFF293CA0) val md_theme_dark_onPrimaryContainer = Color(0xFFDEE0FF) val md_theme_dark_secondary = Color(0xFFC3C5DD) val md_theme_dark_onSecondary = Color(0xFF2D2F42) val md_theme_dark_secondaryContainer = Color(0xFF434659) val md_theme_dark_onSecondaryContainer = Color(0xFFE0E1F9) val md_theme_dark_tertiary = Color(0xFFE6BAD7) val md_theme_dark_onTertiary = Color(0xFF44263D) val md_theme_dark_tertiaryContainer = Color(0xFF5D3C55) val md_theme_dark_onTertiaryContainer = Color(0xFFFFD7F1) 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(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF1B1B1F) val md_theme_dark_onBackground = Color(0xFFE4E1E6) val md_theme_dark_surface = Color(0xFF1B1B1F) val md_theme_dark_onSurface = Color(0xFFE4E1E6) val md_theme_dark_surfaceVariant = Color(0xFF46464F) val md_theme_dark_onSurfaceVariant = Color(0xFFC7C5D0) val md_theme_dark_outline = Color(0xFF90909A) val md_theme_dark_inverseOnSurface = Color(0xFF1B1B1F) val md_theme_dark_inverseSurface = Color(0xFFE4E1E6) val md_theme_dark_inversePrimary = Color(0xFF4355B9) val md_theme_dark_surfaceTint = Color(0xFFBAC3FF) val md_theme_dark_outlineVariant = Color(0xFF46464F) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/ui/theme/Theme.kt
3921158887
/* * Copyright (C) 2023 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.example.unscramble.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 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, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, outlineVariant = md_theme_light_outlineVariant, scrim = md_theme_light_scrim, ) 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, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, outlineVariant = md_theme_dark_outlineVariant, scrim = md_theme_dark_scrim, ) @Composable fun UnscrambleTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ // Dynamic color in this app is turned off for learning purposes dynamicColor: Boolean = false, 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 -> DarkColors else -> LightColors } 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, shapes = Shapes ) }
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/ui/theme/Type.kt
1022459190
/* * Copyright (C) 2023 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.example.unscramble.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( headlineMedium = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Bold, fontSize = 28.sp, lineHeight = 36.sp, letterSpacing = 0.5.sp ) )
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/MainActivity.kt
225548698
/* * Copyright (C) 2023 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.example.unscramble import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import com.example.unscramble.ui.GameScreen import com.example.unscramble.ui.theme.UnscrambleTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { UnscrambleTheme { Surface( modifier = Modifier.fillMaxSize(), ) { GameScreen() } } } } }
AndroidLearning/compose-training-unscramble/app/src/main/java/com/example/unscramble/data/WordsData.kt
3981409104
/* * Copyright (C) 2023 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.example.unscramble.data const val MAX_NO_OF_WORDS = 10 const val SCORE_INCREASE = 20 // Set with all the words for the Game val allWords: Set<String> = setOf( "animal", "auto", "anecdote", "alphabet", "all", "awesome", "arise", "balloon", "basket", "bench", "best", "birthday", "book", "briefcase", "camera", "camping", "candle", "cat", "cauliflower", "chat", "children", "class", "classic", "classroom", "coffee", "colorful", "cookie", "creative", "cruise", "dance", "daytime", "dinosaur", "doorknob", "dine", "dream", "dusk", "eating", "elephant", "emerald", "eerie", "electric", "finish", "flowers", "follow", "fox", "frame", "free", "frequent", "funnel", "green", "guitar", "grocery", "glass", "great", "giggle", "haircut", "half", "homemade", "happen", "honey", "hurry", "hundred", "ice", "igloo", "invest", "invite", "icon", "introduce", "joke", "jovial", "journal", "jump", "join", "kangaroo", "keyboard", "kitchen", "koala", "kind", "kaleidoscope", "landscape", "late", "laugh", "learning", "lemon", "letter", "lily", "magazine", "marine", "marshmallow", "maze", "meditate", "melody", "minute", "monument", "moon", "motorcycle", "mountain", "music", "north", "nose", "night", "name", "never", "negotiate", "number", "opposite", "octopus", "oak", "order", "open", "polar", "pack", "painting", "person", "picnic", "pillow", "pizza", "podcast", "presentation", "puppy", "puzzle", "recipe", "release", "restaurant", "revolve", "rewind", "room", "run", "secret", "seed", "ship", "shirt", "should", "small", "spaceship", "stargazing", "skill", "street", "style", "sunrise", "taxi", "tidy", "timer", "together", "tooth", "tourist", "travel", "truck", "under", "useful", "unicorn", "unique", "uplift", "uniform", "vase", "violin", "visitor", "vision", "volume", "view", "walrus", "wander", "world", "winter", "well", "whirlwind", "x-ray", "xylophone", "yoga", "yogurt", "yoyo", "you", "year", "yummy", "zebra", "zigzag", "zoology", "zone", "zeal" )
AndroidLearning/compose-training-courses/app/src/androidTest/java/com/example/courses/ExampleInstrumentedTest.kt
2047375638
package com.example.courses 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.courses", appContext.packageName) } }
AndroidLearning/compose-training-courses/app/src/test/java/com/example/courses/ExampleUnitTest.kt
4120481196
package com.example.courses 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) } }
AndroidLearning/compose-training-courses/app/src/main/java/com/example/courses/ui/theme/Color.kt
1336062555
package com.example.courses.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)
AndroidLearning/compose-training-courses/app/src/main/java/com/example/courses/ui/theme/Theme.kt
2785098481
package com.example.courses.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 BasicandroidkotlincomposetrainingcoursesTheme( 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 ) }
AndroidLearning/compose-training-courses/app/src/main/java/com/example/courses/ui/theme/Type.kt
3732056946
package com.example.courses.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 ) */ )
AndroidLearning/compose-training-courses/app/src/main/java/com/example/courses/MainActivity.kt
2002024010
package com.example.courses import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.material3.Card import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme 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.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.courses.data.DataSource import com.example.courses.model.Topic import com.example.courses.ui.theme.BasicandroidkotlincomposetrainingcoursesTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BasicandroidkotlincomposetrainingcoursesTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { } } } } } @Composable fun TopicCard(topic: Topic, modifier: Modifier = Modifier) { Card { Row { Box() { Image( painter = painterResource(id = topic.topicImg), contentDescription = stringResource(id = topic.topicName), modifier = Modifier .size(height = 68.dp, width = 68.dp) .aspectRatio(1f), contentScale = ContentScale.Crop ) } Column { Text( text = stringResource(id = topic.topicName), modifier = Modifier.padding( start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp ), style = MaterialTheme.typography.bodyMedium ) Row( verticalAlignment = Alignment.CenterVertically ) { Icon( painter = painterResource(id = R.drawable.ic_grain), contentDescription = null, modifier = Modifier.padding(start = 16.dp) ) Text( text = topic.topicSize.toString(), style = MaterialTheme.typography.labelMedium, modifier = Modifier.padding(start =8.dp) ) } } } } } @Composable fun TopicGrid(topicList: List<Topic>, modifier: Modifier = Modifier) { LazyVerticalGrid( columns = GridCells.Fixed(2), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { items(topicList) { TopicCard( topic = it ) } } } @Preview @Composable fun C() { TopicGrid(topicList = DataSource.topics) }
AndroidLearning/compose-training-courses/app/src/main/java/com/example/courses/model/Topic.kt
3251971736
package com.example.courses.model import androidx.annotation.DrawableRes import androidx.annotation.StringRes data class Topic( @StringRes val topicName: Int, val topicSize: Int, @DrawableRes val topicImg: Int )
AndroidLearning/compose-training-courses/app/src/main/java/com/example/courses/data/DataSource.kt
216773392
package com.example.courses.data import com.example.courses.R import com.example.courses.model.Topic object DataSource { val topics = listOf( Topic(R.string.architecture, 58, R.drawable.architecture), Topic(R.string.crafts, 121, R.drawable.crafts), Topic(R.string.business, 78, R.drawable.business), Topic(R.string.culinary, 118, R.drawable.culinary), Topic(R.string.design, 423, R.drawable.design), Topic(R.string.fashion, 92, R.drawable.fashion), Topic(R.string.film, 165, R.drawable.film), Topic(R.string.gaming, 164, R.drawable.gaming), Topic(R.string.drawing, 326, R.drawable.drawing), Topic(R.string.lifestyle, 305, R.drawable.lifestyle), Topic(R.string.music, 212, R.drawable.music), Topic(R.string.painting, 172, R.drawable.painting), Topic(R.string.photography, 321, R.drawable.photography), Topic(R.string.tech, 118, R.drawable.tech) ) }
AndroidLearning/BookShelf/app/src/androidTest/java/com/example/bookshelf/ExampleInstrumentedTest.kt
2259988401
package com.example.bookshelf 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.bookshelf", appContext.packageName) } }
AndroidLearning/BookShelf/app/src/test/java/com/example/bookshelf/ExampleUnitTest.kt
2080167861
package com.example.bookshelf 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) } }
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/ui/screens/BookViewModel.kt
189894598
package com.example.bookshelf.ui.screens import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel sealed interface BookUiState { //todo change book:String to book:Book data class Success(val book: String) : BookUiState data object Loading : BookUiState data object Error : BookUiState } class BookViewModel (): ViewModel() { val bookUiState: MutableState<BookUiState> = mutableStateOf(BookUiState.Loading) }
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/ui/screens/HomeScreen.kt
2985794539
package com.example.bookshelf.ui.screens
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/ui/theme/Color.kt
803297204
package com.example.bookshelf.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)
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/ui/theme/Theme.kt
2942867426
package com.example.bookshelf.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 BookShelfTheme( 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 ) }
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/ui/theme/Type.kt
3222136357
package com.example.bookshelf.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 ) */ )
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/ui/BookshelfApp.kt
469784408
package com.example.bookshelf.ui import androidx.compose.runtime.Composable @Composable fun BookShelfApp() { }
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/MainActivity.kt
220641750
package com.example.bookshelf 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 com.example.bookshelf.ui.theme.BookShelfTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { BookShelfTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { } } } } }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/ui/MarsPhotosApp.kt
3601857580
/* * Copyright (C) 2023 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. */ @file:OptIn(ExperimentalMaterial3Api::class) package com.example.marsphotos.ui import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.res.stringResource import androidx.lifecycle.viewmodel.compose.viewModel import com.example.marsphotos.R import com.example.marsphotos.ui.screens.HomeScreen import com.example.marsphotos.ui.screens.MarsViewModel @Composable fun MarsPhotosApp() { val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior() Scaffold( modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection), topBar = { MarsTopAppBar(scrollBehavior = scrollBehavior) } ) { Surface( modifier = Modifier.fillMaxSize() ) { val marsViewModel: MarsViewModel = viewModel(factory = MarsViewModel.Factory) HomeScreen( retryAction = marsViewModel::getMarsPhotos, marsUiState = marsViewModel.marsUiState, contentPadding = it, ) } } } @Composable fun MarsTopAppBar(scrollBehavior: TopAppBarScrollBehavior, modifier: Modifier = Modifier) { CenterAlignedTopAppBar( scrollBehavior = scrollBehavior, title = { Text( text = stringResource(R.string.app_name), style = MaterialTheme.typography.headlineSmall, ) }, modifier = modifier ) }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/ui/screens/MarsViewModel.kt
1901137524
/* * Copyright (C) 2023 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.example.marsphotos.ui.screens import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.example.marsphotos.MarsPhotosApplication import com.example.marsphotos.data.MarsPhotosRepository import com.example.marsphotos.data.NetworkMarsPhotosRepository import com.example.marsphotos.network.MarsPhoto import kotlinx.coroutines.launch import java.io.IOException sealed interface MarsUiState { data class Success(val photos: List<MarsPhoto>) : MarsUiState object Error : MarsUiState object Loading : MarsUiState } class MarsViewModel(private val marsPhotosRepository: MarsPhotosRepository) : ViewModel() { /** The mutable State that stores the status of the most recent request */ var marsUiState: MarsUiState by mutableStateOf(MarsUiState.Loading) private set /** * Call getMarsPhotos() on init so we can display status immediately. */ init { getMarsPhotos() } /** * Gets Mars photos information from the Mars API Retrofit service and updates the * [MarsPhoto] [List] [MutableList]. */ fun getMarsPhotos() { viewModelScope.launch { marsUiState = try { val listResult = marsPhotosRepository.getMarsPhotos() MarsUiState.Success(listResult) } catch (e: IOException) { MarsUiState.Error } } } companion object { val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val application = (this[APPLICATION_KEY] as MarsPhotosApplication) val marsPhotosRepository = application.container.marsPhotosRepository MarsViewModel(marsPhotosRepository = marsPhotosRepository) } } } }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/ui/screens/HomeScreen.kt
2116001826
/* * Copyright (C) 2023 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.example.marsphotos.ui.screens import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.material3.Button import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import com.example.marsphotos.R import com.example.marsphotos.network.MarsPhoto import com.example.marsphotos.ui.theme.MarsPhotosTheme @Composable fun HomeScreen( marsUiState: MarsUiState, retryAction: () -> Unit, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp), ) { when (marsUiState) { is MarsUiState.Loading -> LoadingScreen(modifier = modifier.fillMaxSize()) is MarsUiState.Success -> PhotosGridScreen( photos = marsUiState.photos, modifier = Modifier.fillMaxSize() ) is MarsUiState.Error -> ErrorScreen( retryAction = { retryAction() }, modifier = modifier.fillMaxSize() ) } } /** * ResultScreen displaying number of photos retrieved. */ @Composable fun ResultScreen(photos: String, modifier: Modifier = Modifier) { Box( contentAlignment = Alignment.Center, modifier = modifier ) { Text(text = photos) } } @Composable fun LoadingScreen(modifier: Modifier = Modifier) { Image( modifier = modifier.size(200.dp), painter = painterResource(R.drawable.loading_img), contentDescription = stringResource(R.string.loading) ) } @Composable fun ErrorScreen( retryAction: () -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Image( painter = painterResource(id = R.drawable.ic_connection_error), contentDescription = "" ) Text(text = stringResource(R.string.loading_failed), modifier = Modifier.padding(16.dp)) Button(onClick = { retryAction.invoke() }) { Text(text = stringResource(id = R.string.retry)) } } } @Composable fun PhotosGridScreen( photos: List<MarsPhoto>, modifier: Modifier = Modifier, contentPadding: PaddingValues = PaddingValues(0.dp), ) { LazyVerticalGrid( columns = GridCells.Adaptive(150.dp), modifier = modifier.padding(horizontal = 4.dp), contentPadding = contentPadding ) { items(items = photos, key = { photo -> photo.id }) { MarsPhotoCard( marsPhoto = it, modifier = modifier .padding(4.dp) .fillMaxWidth() .aspectRatio(1.5f) ) } } } @Composable fun MarsPhotoCard(marsPhoto: MarsPhoto, modifier: Modifier = Modifier) { Card( modifier = modifier, elevation = CardDefaults.cardElevation(defaultElevation = 8.dp) ) { AsyncImage( model = ImageRequest.Builder(context = LocalContext.current) .data(marsPhoto.imgSrc) .crossfade(true) .build(), contentScale = ContentScale.Crop, error = painterResource(R.drawable.ic_broken_image), placeholder = painterResource(R.drawable.loading_img), contentDescription = stringResource(id = R.string.mars_photo), modifier = Modifier.fillMaxWidth() ) } } @Preview(showBackground = true) @Composable fun ResultScreenPreview() { MarsPhotosTheme { ResultScreen(stringResource(R.string.placeholder_result)) } } @Preview(showBackground = true, showSystemUi = true) @Composable fun PhotosGridScreenPreview() { MarsPhotosTheme { val mockData = List(10) { MarsPhoto("$it", "") } PhotosGridScreen(mockData) } }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/ui/theme/Shape.kt
3644327756
/* * Copyright (C) 2023 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.example.marsphotos.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(16.dp), )
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/ui/theme/Color.kt
193482220
/* * Copyright (C) 2023 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.example.marsphotos.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)
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/ui/theme/Theme.kt
2455326380
/* * Copyright (C) 2023 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.example.marsphotos.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 ) @Composable fun MarsPhotosTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ // Dynamic color in this app is turned off for learning purposes dynamicColor: Boolean = false, 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, shapes = Shapes, content = content ) }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/ui/theme/Type.kt
1765368552
/* * Copyright (C) 2023 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.example.marsphotos.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 ) )
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/MainActivity.kt
3974977120
/* * Copyright (C) 2023 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.example.marsphotos import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.marsphotos.ui.MarsPhotosApp import com.example.marsphotos.ui.theme.MarsPhotosTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { MarsPhotosTheme { Surface( modifier = Modifier.fillMaxSize(), ) { MarsPhotosApp() } } } } } @Preview @Composable fun Mu() { MarsPhotosApp() }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/network/MarsApiService.kt
1888731020
package com.example.marsphotos.network import retrofit2.http.GET interface MarsApiService { @GET("photos") suspend fun getPhotos(): List<MarsPhoto> }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/network/MarsPhoto.kt
2201722993
package com.example.marsphotos.network import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class MarsPhoto( @SerialName(value = "id") val id: String, @SerialName(value = "img_src") val imgSrc: String )
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/data/MarsPhotosRepository.kt
2333906498
package com.example.marsphotos.data import com.example.marsphotos.network.MarsApiService import com.example.marsphotos.network.MarsPhoto interface MarsPhotosRepository { suspend fun getMarsPhotos(): List<MarsPhoto> } class NetworkMarsPhotosRepository( private val marsApiService: MarsApiService ):MarsPhotosRepository{ override suspend fun getMarsPhotos()=marsApiService.getPhotos() }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/data/AppContainer.kt
984394108
package com.example.marsphotos.data import com.example.marsphotos.network.MarsApiService import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import retrofit2.Retrofit interface AppContainer { val marsPhotosRepository:MarsPhotosRepository } class DefaultAppContainer:AppContainer{ private val baseUrl = "https://android-kotlin-fun-mars-server.appspot.com" private val retrofit: Retrofit = Retrofit.Builder() .addConverterFactory(Json.asConverterFactory("application/json".toMediaType())) .baseUrl(baseUrl) .build() private val retrofitService: MarsApiService by lazy { retrofit.create(MarsApiService::class.java) } override val marsPhotosRepository:MarsPhotosRepository by lazy { NetworkMarsPhotosRepository(retrofitService) } }
AndroidLearning/compose-training-mars-photos/app/src/main/java/com/example/marsphotos/MarsPhotosApplication.kt
2229411459
package com.example.marsphotos import android.app.Application import com.example.marsphotos.data.AppContainer import com.example.marsphotos.data.DefaultAppContainer class MarsPhotosApplication:Application() { lateinit var container: AppContainer override fun onCreate() { super.onCreate() container=DefaultAppContainer() } }
AndroidLearning/compose-training-reply-app/app/src/androidTest/java/com/example/reply/test/ComposeTestRuleExtensions.kt
3060750998
/* * Copyright (C) 2023 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.example.reply.test import androidx.activity.ComponentActivity import androidx.annotation.StringRes import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.junit4.AndroidComposeTestRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.test.ext.junit.rules.ActivityScenarioRule /** * Finds a semantics node with the given string resource id. * * The [onNodeWithText] finder provided by compose ui test API, doesn't support usage of * string resource id to find the semantics node. This extension function accesses string resource * using underlying activity property and passes it to [onNodeWithText] function as argument and * returns the [SemanticsNodeInteraction] object. */ fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A>.onNodeWithStringId( @StringRes id: Int ): SemanticsNodeInteraction = onNodeWithText(activity.getString(id)) /** * Finds a semantics node from the content description with the given string resource id. * * The [onNodeWithContentDescription] finder provided by compose ui test API, doesn't support usage * of string resource id to find the semantics node from the node's content description. * This extension function accesses string resource using underlying activity property * and passes it to [onNodeWithContentDescription] function as argument and * returns the [SemanticsNodeInteraction] object. */ fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A> .onNodeWithContentDescriptionForStringId( @StringRes id: Int ): SemanticsNodeInteraction = onNodeWithContentDescription(activity.getString(id)) /** * Finds a semantics node from the content description with the given string resource id. * * The [onNodeWithTag] finder provided by compose ui test API, doesn't support usage of * string resource id to find the semantics node from the node's test tag. * This extension function accesses string resource using underlying activity property * and passes it to [onNodeWithTag] function as argument and * returns the [SemanticsNodeInteraction] object. */ fun <A : ComponentActivity> AndroidComposeTestRule<ActivityScenarioRule<A>, A> .onNodeWithTagForStringId( @StringRes id: Int ): SemanticsNodeInteraction = onNodeWithTag(activity.getString(id))
AndroidLearning/compose-training-reply-app/app/src/androidTest/java/com/example/reply/test/ReplyAppStateRestorationTest.kt
500978582
package com.example.reply.test import androidx.activity.ComponentActivity import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.StateRestorationTester import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import com.example.reply.R import com.example.reply.data.local.LocalEmailsDataProvider import com.example.reply.ui.ReplyApp import org.junit.Rule import org.junit.Test class ReplyAppStateRestorationTest { /** * Note: To access to an empty activity, the code uses ComponentActivity instead of * MainActivity. */ @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun compactDevice_selectedEmailEmailRetained_afterConfigChange() { val stateRestorationTester = StateRestorationTester(composeTestRule) stateRestorationTester.setContent { ReplyApp(windowSize = WindowWidthSizeClass.Compact) } composeTestRule.onNodeWithText( composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[2].body) ).assertIsDisplayed() composeTestRule.onNodeWithText( composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[2].subject) ).performClick() composeTestRule.onNodeWithText( composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[2].body) ).assertExists() stateRestorationTester.emulateSavedInstanceStateRestore() // Verify that it still shows the detailed screen for the same email composeTestRule.onNodeWithContentDescriptionForStringId( R.string.navigation_back ).assertExists() composeTestRule.onNodeWithText( composeTestRule.activity.getString(LocalEmailsDataProvider.allEmails[2].body) ).assertExists() } }
AndroidLearning/compose-training-reply-app/app/src/androidTest/java/com/example/reply/test/ReplyAppTest.kt
2826593349
package com.example.reply.test import androidx.activity.ComponentActivity import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.ui.test.junit4.createAndroidComposeRule import com.example.reply.R import com.example.reply.ui.ReplyApp import org.junit.Rule import org.junit.Test class ReplyAppTest { @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() @Test fun compactDevice_verifyUsingBottomNavigation() { // Set up compact window composeTestRule.setContent { ReplyApp( windowSize = WindowWidthSizeClass.Compact ) } composeTestRule.onNodeWithStringId( R.string.navigation_bottom ).assertExists() } @Test fun mediumDevice_verifyUsingNavigationRail() { // Set up medium window composeTestRule.setContent { ReplyApp( windowSize = WindowWidthSizeClass.Medium ) } // Navigation rail is displayed composeTestRule.onNodeWithTagForStringId( R.string.navigation_rail ).assertExists() } @Test fun expandedDevice_verifyUsingNavigationDrawer() { // Set up expanded window composeTestRule.setContent { ReplyApp( windowSize = WindowWidthSizeClass.Expanded ) } // Navigation drawer is displayed composeTestRule.onNodeWithTagForStringId( R.string.navigation_drawer ).assertExists() } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyViewModel.kt
1286589960
/* * Copyright (C) 2023 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.example.reply.ui import androidx.lifecycle.ViewModel import com.example.reply.data.Email import com.example.reply.data.MailboxType import com.example.reply.data.local.LocalEmailsDataProvider import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update class ReplyViewModel : ViewModel() { private val _uiState = MutableStateFlow(ReplyUiState()) val uiState: StateFlow<ReplyUiState> = _uiState init { initializeUIState() } private fun initializeUIState() { val mailboxes: Map<MailboxType, List<Email>> = LocalEmailsDataProvider.allEmails.groupBy { it.mailbox } _uiState.value = ReplyUiState( mailboxes = mailboxes, currentSelectedEmail = mailboxes[MailboxType.Inbox]?.get(0) ?: LocalEmailsDataProvider.defaultEmail ) } fun updateDetailsScreenStates(email: Email) { _uiState.update { it.copy( currentSelectedEmail = email, isShowingHomepage = false ) } } fun resetHomeScreenStates() { _uiState.update { it.copy( currentSelectedEmail = it.mailboxes[it.currentMailbox]?.get(0) ?: LocalEmailsDataProvider.defaultEmail, isShowingHomepage = true ) } } fun updateCurrentMailbox(mailboxType: MailboxType) { _uiState.update { it.copy( currentMailbox = mailboxType ) } } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyApp.kt
1271135090
/* * Copyright (C) 2023 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.example.reply.ui import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.ui.Modifier import androidx.lifecycle.viewmodel.compose.viewModel import com.example.reply.data.Email import com.example.reply.data.MailboxType import com.example.reply.ui.utils.ReplyContentType import com.example.reply.ui.utils.ReplyNavigationType @Composable fun ReplyApp( windowSize: WindowWidthSizeClass, modifier: Modifier = Modifier, ) { val navigationType: ReplyNavigationType val contentType: ReplyContentType val viewModel: ReplyViewModel = viewModel() val replyUiState = viewModel.uiState.collectAsState().value when (windowSize) { WindowWidthSizeClass.Compact -> { navigationType = ReplyNavigationType.BOTTOM_NAVIGATION contentType = ReplyContentType.LIST_ONLY } WindowWidthSizeClass.Medium -> { navigationType = ReplyNavigationType.NAVIGATION_RAIL contentType = ReplyContentType.LIST_ONLY } WindowWidthSizeClass.Expanded -> { navigationType = ReplyNavigationType.PERMANENT_NAVIGATION_DRAWER contentType = ReplyContentType.LIST_AND_DETAIL } else -> { navigationType = ReplyNavigationType.BOTTOM_NAVIGATION contentType = ReplyContentType.LIST_ONLY } } ReplyHomeScreen( navigationType = navigationType, contentType = contentType, replyUiState = replyUiState, onTabPressed = { mailboxType: MailboxType -> viewModel.updateCurrentMailbox(mailboxType = mailboxType) viewModel.resetHomeScreenStates() }, onEmailCardPressed = { email: Email -> viewModel.updateDetailsScreenStates( email = email ) }, onDetailScreenBackPressed = { viewModel.resetHomeScreenStates() }, modifier = modifier ) }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyHomeContent.kt
95526979
/* * Copyright (C) 2023 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.example.reply.ui import android.app.Activity import androidx.annotation.DrawableRes import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.local.LocalAccountsDataProvider @Composable fun ReplyListOnlyContent( replyUiState: ReplyUiState, onEmailCardPressed: (Email) -> Unit, modifier: Modifier = Modifier ) { val emails = replyUiState.currentMailboxEmails LazyColumn( modifier = modifier, verticalArrangement = Arrangement.spacedBy( dimensionResource(R.dimen.email_list_item_vertical_spacing) ) ) { item { ReplyHomeTopBar( modifier = Modifier .fillMaxWidth() .padding(vertical = dimensionResource(R.dimen.topbar_padding_vertical)) ) } items(emails, key = { email -> email.id }) { email -> ReplyEmailListItem( email = email, selected = false, onCardClick = { onEmailCardPressed(email) } ) } } } @Composable fun ReplyListAndDetailContent( replyUiState: ReplyUiState, onEmailCardPressed: (Email) -> Unit, modifier: Modifier = Modifier ) { val emails = replyUiState.currentMailboxEmails Row(modifier = modifier) { LazyColumn( modifier = Modifier .weight(1f) .padding( end = dimensionResource(R.dimen.list_and_detail_list_padding_end), top = dimensionResource(R.dimen.list_and_detail_list_padding_top) ), verticalArrangement = Arrangement.spacedBy( dimensionResource(R.dimen.email_list_item_vertical_spacing) ) ) { items(emails, key = { email -> email.id }) { email -> ReplyEmailListItem( email = email, selected = replyUiState.currentSelectedEmail.id == email.id, onCardClick = { onEmailCardPressed(email) }, ) } } val activity = LocalContext.current as Activity ReplyDetailsScreen( replyUiState = replyUiState, modifier = Modifier.weight(1f), onBackPressed = {} ) } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun ReplyEmailListItem( email: Email, selected: Boolean, onCardClick: () -> Unit, modifier: Modifier = Modifier ) { Card( modifier = modifier, colors = CardDefaults.cardColors( containerColor = if (selected) { MaterialTheme.colorScheme.primaryContainer } else { MaterialTheme.colorScheme.secondaryContainer } ), onClick = onCardClick ) { Column( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.email_list_item_inner_padding)) ) { ReplyEmailItemHeader( email, Modifier.fillMaxWidth() ) Text( text = stringResource(email.subject), style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.padding( top = dimensionResource(R.dimen.email_list_item_header_subject_spacing), bottom = dimensionResource(R.dimen.email_list_item_subject_body_spacing) ), ) Text( text = stringResource(email.body), style = MaterialTheme.typography.bodyMedium, maxLines = 2, color = MaterialTheme.colorScheme.onSurfaceVariant, overflow = TextOverflow.Ellipsis ) } } } @Composable private fun ReplyEmailItemHeader(email: Email, modifier: Modifier = Modifier) { Row(modifier = modifier) { ReplyProfileImage( drawableResource = email.sender.avatar, description = stringResource(email.sender.firstName) + " " + stringResource(email.sender.lastName), modifier = Modifier.size(dimensionResource(R.dimen.email_header_profile_size)) ) Column( modifier = Modifier .weight(1f) .padding( horizontal = dimensionResource(R.dimen.email_header_content_padding_horizontal), vertical = dimensionResource(R.dimen.email_header_content_padding_vertical) ), verticalArrangement = Arrangement.Center ) { Text( text = stringResource(email.sender.firstName), style = MaterialTheme.typography.labelMedium ) Text( text = stringResource(email.createdAt), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.outline ) } } } @Composable fun ReplyProfileImage( @DrawableRes drawableResource: Int, description: String, modifier: Modifier = Modifier, ) { Box(modifier = modifier) { Image( modifier = Modifier.clip(CircleShape), painter = painterResource(drawableResource), contentDescription = description, ) } } @Composable fun ReplyLogo( modifier: Modifier = Modifier, color: Color = MaterialTheme.colorScheme.primary ) { Image( painter = painterResource(R.drawable.logo), contentDescription = stringResource(R.string.logo), colorFilter = ColorFilter.tint(color), modifier = modifier ) } @Composable private fun ReplyHomeTopBar(modifier: Modifier = Modifier) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = modifier ) { ReplyLogo( modifier = Modifier .size(dimensionResource(R.dimen.topbar_logo_size)) .padding(start = dimensionResource(R.dimen.topbar_logo_padding_start)) ) ReplyProfileImage( drawableResource = LocalAccountsDataProvider.defaultAccount.avatar, description = stringResource(R.string.profile), modifier = Modifier .padding(end = dimensionResource(R.dimen.topbar_profile_image_padding_end)) .size(dimensionResource(R.dimen.topbar_profile_image_size)) ) } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/utils/WindowStateUtils.kt
1987175728
/* * Copyright (C) 2023 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.example.reply.ui.utils /** * Different type of navigation supported by app depending on size and state. */ enum class ReplyNavigationType { BOTTOM_NAVIGATION, NAVIGATION_RAIL, PERMANENT_NAVIGATION_DRAWER } enum class ReplyContentType { LIST_ONLY, LIST_AND_DETAIL }