content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
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/test/java/com/ozcanbayram/logren/ExampleUnitTest.kt
3868841980
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/Details.kt
626148930
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/adapter/TermsAdapter.kt
2455277767
package com.ozcanbayram.logren.model data class Term(val term : String, val explanation : String) { }
Logren/app/src/main/java/com/ozcanbayram/logren/model/Term.kt
737079388
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/ActivityRegsiter.kt
2448530771
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/MainActivity.kt
1049085810
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/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 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() } } } }
Logren/app/src/main/java/com/ozcanbayram/logren/view/LoginActivity.kt
2121021287
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/ui/test/GameViewModelTest.kt
3765142397
/* * 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/test/java/com/example/unscramble/data/WordsData.kt
3865389887
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/GameUiState.kt
3219515172
/* * 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/GameScreen.kt
4224056311
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/GameViewModel.kt
891328432
/* * 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/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.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/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 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/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 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/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 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/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.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-unscramble/app/src/main/java/com/example/unscramble/data/WordsData.kt
3981409104
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/androidTest/java/com/example/courses/ExampleInstrumentedTest.kt
2047375638
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/test/java/com/example/courses/ExampleUnitTest.kt
4120481196
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/Color.kt
1336062555
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/Theme.kt
2785098481
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/ui/theme/Type.kt
3732056946
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/MainActivity.kt
2002024010
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/model/Topic.kt
3251971736
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/compose-training-courses/app/src/main/java/com/example/courses/data/DataSource.kt
216773392
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/androidTest/java/com/example/bookshelf/ExampleInstrumentedTest.kt
2259988401
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/test/java/com/example/bookshelf/ExampleUnitTest.kt
2080167861
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/BookViewModel.kt
189894598
package com.example.bookshelf.ui.screens
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/ui/screens/HomeScreen.kt
2985794539
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/Color.kt
803297204
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/Theme.kt
2942867426
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/theme/Type.kt
3222136357
package com.example.bookshelf.ui import androidx.compose.runtime.Composable @Composable fun BookShelfApp() { }
AndroidLearning/BookShelf/app/src/main/java/com/example/bookshelf/ui/BookshelfApp.kt
469784408
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/BookShelf/app/src/main/java/com/example/bookshelf/MainActivity.kt
220641750
/* * 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/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. */ 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/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.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/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.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/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.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/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 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/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 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/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 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/MainActivity.kt
3974977120
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/MarsApiService.kt
1888731020
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/network/MarsPhoto.kt
2201722993
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/MarsPhotosRepository.kt
2333906498
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/data/AppContainer.kt
984394108
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-mars-photos/app/src/main/java/com/example/marsphotos/MarsPhotosApplication.kt
2229411459
/* * 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/ComposeTestRuleExtensions.kt
3060750998
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/ReplyAppStateRestorationTest.kt
500978582
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/androidTest/java/com/example/reply/test/ReplyAppTest.kt
2826593349
/* * 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/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.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/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 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/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.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 }
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 import android.app.Activity import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Drafts import androidx.compose.material.icons.filled.Inbox import androidx.compose.material.icons.filled.Report import androidx.compose.material.icons.filled.Send import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.NavigationBar import androidx.compose.material3.NavigationBarItem import androidx.compose.material3.NavigationDrawerItem import androidx.compose.material3.NavigationDrawerItemDefaults import androidx.compose.material3.NavigationRail import androidx.compose.material3.NavigationRailItem import androidx.compose.material3.PermanentDrawerSheet import androidx.compose.material3.PermanentNavigationDrawer import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.MailboxType import com.example.reply.data.local.LocalAccountsDataProvider import com.example.reply.ui.utils.ReplyContentType import com.example.reply.ui.utils.ReplyNavigationType @Composable fun ReplyHomeScreen( navigationType: ReplyNavigationType, contentType: ReplyContentType, replyUiState: ReplyUiState, onTabPressed: (MailboxType) -> Unit, onEmailCardPressed: (Email) -> Unit, onDetailScreenBackPressed: () -> Unit, modifier: Modifier = Modifier ) { val navigationItemContentList = listOf( NavigationItemContent( mailboxType = MailboxType.Inbox, icon = Icons.Default.Inbox, text = stringResource(id = R.string.tab_inbox) ), NavigationItemContent( mailboxType = MailboxType.Sent, icon = Icons.Default.Send, text = stringResource(id = R.string.tab_sent) ), NavigationItemContent( mailboxType = MailboxType.Drafts, icon = Icons.Default.Drafts, text = stringResource(id = R.string.tab_drafts) ), NavigationItemContent( mailboxType = MailboxType.Spam, icon = Icons.Default.Report, text = stringResource(id = R.string.tab_spam) ) ) if (navigationType == ReplyNavigationType.PERMANENT_NAVIGATION_DRAWER) { val navigationDrawerContentDescription = stringResource(R.string.navigation_drawer) PermanentNavigationDrawer( modifier = Modifier.testTag(navigationDrawerContentDescription), drawerContent = { PermanentDrawerSheet( Modifier.width(dimensionResource(R.dimen.drawer_width)) ) { NavigationDrawerContent( selectedDestination = replyUiState.currentMailbox, onTabPressed = onTabPressed, navigationItemContentList = navigationItemContentList, modifier = Modifier .wrapContentWidth() .fillMaxHeight() .background(MaterialTheme.colorScheme.inverseOnSurface) .padding(dimensionResource(R.dimen.drawer_padding_content)) ) } }, ) { ReplyAppContent( contentType = contentType, navigationType = navigationType, replyUiState = replyUiState, onTabPressed = onTabPressed, onEmailCardPressed = onEmailCardPressed, navigationItemContentList = navigationItemContentList, modifier = modifier ) } } else { if (replyUiState.isShowingHomepage) { ReplyAppContent( contentType = contentType, navigationType = navigationType, replyUiState = replyUiState, onTabPressed = onTabPressed, onEmailCardPressed = onEmailCardPressed, navigationItemContentList = navigationItemContentList, modifier = modifier ) } else { ReplyDetailsScreen( replyUiState = replyUiState, onBackPressed = onDetailScreenBackPressed, modifier = modifier, true ) } } } @Composable private fun ReplyAppContent( navigationType: ReplyNavigationType, contentType: ReplyContentType, replyUiState: ReplyUiState, onTabPressed: ((MailboxType) -> Unit), onEmailCardPressed: (Email) -> Unit, navigationItemContentList: List<NavigationItemContent>, modifier: Modifier = Modifier, ) { val activity = LocalContext.current as Activity Box(modifier = modifier) { Row(modifier = Modifier.fillMaxSize()) { AnimatedVisibility(visible = navigationType == ReplyNavigationType.NAVIGATION_RAIL) { val navigationRailContentDescription = stringResource(R.string.navigation_rail) ReplyNavigationRail( currentTab = replyUiState.currentMailbox, onTabPressed = onTabPressed, navigationItemContentList = navigationItemContentList, modifier = Modifier .testTag(navigationRailContentDescription) ) } Column( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.inverseOnSurface) ) { if (contentType == ReplyContentType.LIST_AND_DETAIL) { ReplyListAndDetailContent( replyUiState = replyUiState, onEmailCardPressed = onEmailCardPressed, modifier = Modifier.weight(1f) ) } else { ReplyListOnlyContent( replyUiState = replyUiState, onEmailCardPressed = onEmailCardPressed, modifier = Modifier .weight(1f) .padding( horizontal = dimensionResource(R.dimen.email_list_only_horizontal_padding) ) ) } AnimatedVisibility( visible = navigationType == ReplyNavigationType.BOTTOM_NAVIGATION ) { val bottomNavigationDescription = stringResource(id = R.string.navigation_bottom) ReplyBottomNavigationBar( currentTab = replyUiState.currentMailbox, onTabPressed = onTabPressed, navigationItemContentList = navigationItemContentList, modifier = Modifier .fillMaxWidth() .testTag(bottomNavigationDescription) ) } } } } } @Composable private fun ReplyNavigationRail( currentTab: MailboxType, onTabPressed: ((MailboxType) -> Unit), navigationItemContentList: List<NavigationItemContent>, modifier: Modifier = Modifier ) { NavigationRail(modifier = modifier) { for (navItem in navigationItemContentList) { NavigationRailItem( selected = currentTab == navItem.mailboxType, onClick = { onTabPressed(navItem.mailboxType) }, icon = { Icon( imageVector = navItem.icon, contentDescription = navItem.text ) } ) } } } @Composable private fun ReplyBottomNavigationBar( currentTab: MailboxType, onTabPressed: ((MailboxType) -> Unit), navigationItemContentList: List<NavigationItemContent>, modifier: Modifier = Modifier ) { NavigationBar(modifier = modifier) { for (navItem in navigationItemContentList) { NavigationBarItem( selected = currentTab == navItem.mailboxType, onClick = { onTabPressed(navItem.mailboxType) }, icon = { Icon( imageVector = navItem.icon, contentDescription = navItem.text ) } ) } } } @Composable private fun NavigationDrawerContent( selectedDestination: MailboxType, onTabPressed: ((MailboxType) -> Unit), navigationItemContentList: List<NavigationItemContent>, modifier: Modifier = Modifier ) { Column(modifier = modifier) { NavigationDrawerHeader( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.profile_image_padding)), ) for (navItem in navigationItemContentList) { NavigationDrawerItem( selected = selectedDestination == navItem.mailboxType, label = { Text( text = navItem.text, modifier = Modifier.padding(horizontal = dimensionResource(R.dimen.drawer_padding_header)) ) }, icon = { Icon( imageVector = navItem.icon, contentDescription = navItem.text ) }, colors = NavigationDrawerItemDefaults.colors( unselectedContainerColor = Color.Transparent ), onClick = { onTabPressed(navItem.mailboxType) } ) } } } @Composable private fun NavigationDrawerHeader( modifier: Modifier = Modifier ) { Row( modifier = modifier, horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { ReplyLogo(modifier = Modifier.size(dimensionResource(R.dimen.reply_logo_size))) ReplyProfileImage( drawableResource = LocalAccountsDataProvider.defaultAccount.avatar, description = stringResource(id = R.string.profile), modifier = Modifier .size(dimensionResource(R.dimen.profile_image_size)) ) } } private data class NavigationItemContent( val mailboxType: MailboxType, val icon: ImageVector, val text: String )
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyHomeScreen.kt
108703493
/* * 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 com.example.reply.data.Email import com.example.reply.data.MailboxType import com.example.reply.data.local.LocalEmailsDataProvider data class ReplyUiState( val mailboxes: Map<MailboxType, List<Email>> = emptyMap(), val currentMailbox: MailboxType = MailboxType.Inbox, val currentSelectedEmail: Email = LocalEmailsDataProvider.defaultEmail, val isShowingHomepage: Boolean = true ) { val currentMailboxEmails: List<Email> by lazy { mailboxes[currentMailbox]!! } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyUiState.kt
1098534396
/* * 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.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF006879) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFA9EDFF) val md_theme_light_onPrimaryContainer = Color(0xFF001F26) val md_theme_light_secondary = Color(0xFF4B6268) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFCEE7EE) val md_theme_light_onSecondaryContainer = Color(0xFF061F24) val md_theme_light_tertiary = Color(0xFF565D7E) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFDDE1FF) val md_theme_light_onTertiaryContainer = Color(0xFF121A37) 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(0xFFFBFCFD) val md_theme_light_onBackground = Color(0xFF191C1D) val md_theme_light_surface = Color(0xFFFBFCFD) val md_theme_light_onSurface = Color(0xFF191C1D) val md_theme_light_surfaceVariant = Color(0xFFDBE4E7) val md_theme_light_onSurfaceVariant = Color(0xFF3F484B) val md_theme_light_outline = Color(0xFF6F797B) val md_theme_light_inverseOnSurface = Color(0xFFEFF1F2) val md_theme_light_inverseSurface = Color(0xFF2E3132) val md_theme_light_inversePrimary = Color(0xFF54D7F3) val md_theme_light_surfaceTint = Color(0xFF006879) val md_theme_light_outlineVariant = Color(0xFFBFC8CB) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFF54D7F3) val md_theme_dark_onPrimary = Color(0xFF003640) val md_theme_dark_primaryContainer = Color(0xFF004E5B) val md_theme_dark_onPrimaryContainer = Color(0xFFA9EDFF) val md_theme_dark_secondary = Color(0xFFB2CBD2) val md_theme_dark_onSecondary = Color(0xFF1C343A) val md_theme_dark_secondaryContainer = Color(0xFF334A50) val md_theme_dark_onSecondaryContainer = Color(0xFFCEE7EE) val md_theme_dark_tertiary = Color(0xFFBEC5EB) val md_theme_dark_onTertiary = Color(0xFF282F4D) val md_theme_dark_tertiaryContainer = Color(0xFF3E4565) val md_theme_dark_onTertiaryContainer = Color(0xFFDDE1FF) 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(0xFF191C1D) val md_theme_dark_onBackground = Color(0xFFE1E3E4) val md_theme_dark_surface = Color(0xFF191C1D) val md_theme_dark_onSurface = Color(0xFFE1E3E4) val md_theme_dark_surfaceVariant = Color(0xFF3F484B) val md_theme_dark_onSurfaceVariant = Color(0xFFBFC8CB) val md_theme_dark_outline = Color(0xFF899295) val md_theme_dark_inverseOnSurface = Color(0xFF191C1D) val md_theme_dark_inverseSurface = Color(0xFFE1E3E4) val md_theme_dark_inversePrimary = Color(0xFF006879) val md_theme_dark_surfaceTint = Color(0xFF54D7F3) val md_theme_dark_outlineVariant = Color(0xFF3F484B) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/theme/Color.kt
1408203468
/* * 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.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.lightColorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme 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 LightColorScheme = 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 DarkColorScheme = 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 ReplyTheme( darkTheme: Boolean = isSystemInDarkTheme(), 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, content = content ) }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/theme/Theme.kt
1794857538
/* * 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.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 val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) )
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/theme/Type.kt
1019064958
/* * 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.widget.Toast import androidx.activity.compose.BackHandler import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.IconButton 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.platform.LocalContext import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.MailboxType @Composable fun ReplyDetailsScreen( replyUiState: ReplyUiState, onBackPressed: () -> Unit, modifier: Modifier = Modifier, isFullScreen: Boolean = false, ) { BackHandler { onBackPressed() } Box(modifier = modifier) { LazyColumn( modifier = Modifier .fillMaxSize() .background(color = MaterialTheme.colorScheme.inverseOnSurface) .padding(top = dimensionResource(R.dimen.detail_card_list_padding_top)) ) { item { if (isFullScreen) { ReplyDetailsScreenTopBar( onBackPressed, replyUiState, Modifier .fillMaxWidth() .padding(bottom = dimensionResource(R.dimen.detail_topbar_padding_bottom)) ) } ReplyEmailDetailsCard( email = replyUiState.currentSelectedEmail, mailboxType = replyUiState.currentMailbox, modifier = if (isFullScreen) { Modifier.padding(horizontal = dimensionResource(R.dimen.detail_card_outer_padding_horizontal)) } else { Modifier.padding(end = dimensionResource(R.dimen.detail_card_outer_padding_horizontal)) } ) } } } } @Composable private fun ReplyDetailsScreenTopBar( onBackButtonClicked: () -> Unit, replyUiState: ReplyUiState, modifier: Modifier = Modifier ) { Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically, ) { IconButton( onClick = onBackButtonClicked, modifier = Modifier .padding(horizontal = dimensionResource(R.dimen.detail_topbar_back_button_padding_horizontal)) .background(MaterialTheme.colorScheme.surface, shape = CircleShape), ) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(id = R.string.navigation_back) ) } Row( horizontalArrangement = Arrangement.Center, modifier = Modifier .fillMaxWidth() .padding(end = dimensionResource(R.dimen.detail_subject_padding_end)) ) { Text( text = stringResource(replyUiState.currentSelectedEmail.subject), style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } @Composable private fun ReplyEmailDetailsCard( email: Email, mailboxType: MailboxType, modifier: Modifier = Modifier, isFullScreen: Boolean = false ) { val context = LocalContext.current val displayToast = { text: String -> Toast.makeText(context, text, Toast.LENGTH_SHORT).show() } Card( modifier = modifier, colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface) ) { Column( modifier = Modifier .fillMaxWidth() .padding(dimensionResource(R.dimen.detail_card_inner_padding)) ) { DetailsScreenHeader( email, Modifier.fillMaxWidth() ) if (isFullScreen) { Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.detail_content_padding_top))) } else { Text( text = stringResource(email.subject), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.outline, modifier = Modifier.padding( top = dimensionResource(R.dimen.detail_content_padding_top), bottom = dimensionResource(R.dimen.detail_expanded_subject_body_spacing) ), ) } Text( text = stringResource(email.body), style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, ) DetailsScreenButtonBar(mailboxType, displayToast) } } } @Composable private fun DetailsScreenButtonBar( mailboxType: MailboxType, displayToast: (String) -> Unit, modifier: Modifier = Modifier ) { Box(modifier = modifier) { when (mailboxType) { MailboxType.Drafts -> ActionButton( text = stringResource(id = R.string.continue_composing), onButtonClicked = displayToast ) MailboxType.Spam -> Row( modifier = Modifier .fillMaxWidth() .padding( vertical = dimensionResource(R.dimen.detail_button_bar_padding_vertical) ), horizontalArrangement = Arrangement.spacedBy( dimensionResource(R.dimen.detail_button_bar_item_spacing) ), ) { ActionButton( text = stringResource(id = R.string.move_to_inbox), onButtonClicked = displayToast, modifier = Modifier.weight(1f) ) ActionButton( text = stringResource(id = R.string.delete), onButtonClicked = displayToast, containIrreversibleAction = true, modifier = Modifier.weight(1f) ) } MailboxType.Sent, MailboxType.Inbox -> Row( modifier = Modifier .fillMaxWidth() .padding( vertical = dimensionResource(R.dimen.detail_button_bar_padding_vertical) ), horizontalArrangement = Arrangement.spacedBy( dimensionResource(R.dimen.detail_button_bar_item_spacing) ), ) { ActionButton( text = stringResource(id = R.string.reply), onButtonClicked = displayToast, modifier = Modifier.weight(1f) ) ActionButton( text = stringResource(id = R.string.reply_all), onButtonClicked = displayToast, modifier = Modifier.weight(1f) ) } } } } @Composable private fun DetailsScreenHeader(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 private fun ActionButton( text: String, onButtonClicked: (String) -> Unit, modifier: Modifier = Modifier, containIrreversibleAction: Boolean = false, ) { Box(modifier = modifier) { Button( onClick = { onButtonClicked(text) }, modifier = Modifier .fillMaxWidth() .padding(vertical = dimensionResource(R.dimen.detail_action_button_padding_vertical)), colors = ButtonDefaults.buttonColors( containerColor = if (containIrreversibleAction) { MaterialTheme.colorScheme.onErrorContainer } else { MaterialTheme.colorScheme.primaryContainer } ) ) { Text( text = text, color = if (containIrreversibleAction) { MaterialTheme.colorScheme.onError } else { MaterialTheme.colorScheme.onSurfaceVariant } ) } } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/ui/ReplyDetailsScreen.kt
903602997
/* * 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 import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.Surface import androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.material3.windowsizeclass.calculateWindowSizeClass import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.example.reply.ui.ReplyApp import com.example.reply.ui.theme.ReplyTheme class MainActivity : ComponentActivity() { @OptIn(ExperimentalMaterial3WindowSizeClassApi::class) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { ReplyTheme { Surface { val windowSize = calculateWindowSizeClass(this) ReplyApp( windowSize = windowSize.widthSizeClass, ) } } } } } @Preview(showBackground = true) @Composable fun ReplyAppCompactPreview() { ReplyTheme { Surface { ReplyApp( windowSize = WindowWidthSizeClass.Compact, ) } } } @Preview(showBackground = true, widthDp = 700) @Composable fun ReplyAppMediumPreview() { ReplyTheme { Surface { ReplyApp(windowSize = WindowWidthSizeClass.Medium) } } } @Preview(showBackground = true, widthDp = 1000) @Composable fun ReplyAppExpandedPreview() { ReplyTheme { Surface { ReplyApp(windowSize = WindowWidthSizeClass.Expanded) } } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/MainActivity.kt
287309706
/* * 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.data import androidx.annotation.StringRes /** * A simple data class to represent an Email */ data class Email( /** Unique ID of the email **/ val id: Long, /** Sender of the email **/ val sender: Account, /** Recipient(s) of the email **/ val recipients: List<Account> = emptyList(), /** Title of the email **/ @StringRes val subject: Int = -1, /** Content of the email **/ @StringRes val body: Int = -1, /** Which mailbox it is in **/ var mailbox: MailboxType = MailboxType.Inbox, /** * Relative duration in which it was created. (e.g. 20 mins ago) * It should be calculated from relative time in the future. * For now it's hard coded to a [String] value. */ @StringRes var createdAt: Int = -1 )
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/Email.kt
594865175
/* * 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.data import androidx.annotation.DrawableRes import androidx.annotation.StringRes /** * A class which represents an account */ data class Account( /** Unique ID of a user **/ val id: Long, /** User's first name **/ @StringRes val firstName: Int, /** User's last name **/ @StringRes val lastName: Int, /** User's email address **/ @StringRes val email: Int, /** User's avatar image resource id **/ @DrawableRes val avatar: Int )
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/Account.kt
2950049882
/* * 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.data.local import com.example.reply.R import com.example.reply.data.Email import com.example.reply.data.MailboxType /** * A static data store of [Email]s. */ object LocalEmailsDataProvider { val allEmails = listOf( Email( id = 0L, sender = LocalAccountsDataProvider.getContactAccountById(9L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_0_subject, body = R.string.email_0_body, createdAt = R.string.email_0_time, ), Email( id = 1L, sender = LocalAccountsDataProvider.getContactAccountById(6L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_1_subject, body = R.string.email_1_body, createdAt = R.string.email_1_time, ), Email( 2L, LocalAccountsDataProvider.getContactAccountById(5L), listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_2_subject, body = R.string.email_2_body, createdAt = R.string.email_2_time, ), Email( 3L, LocalAccountsDataProvider.getContactAccountById(8L), listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_3_subject, body = R.string.email_3_body, createdAt = R.string.email_3_time, mailbox = MailboxType.Sent, ), Email( id = 4L, sender = LocalAccountsDataProvider.getContactAccountById(11L), subject = R.string.email_4_subject, body = R.string.email_4_body, createdAt = R.string.email_4_time, ), Email( id = 5L, sender = LocalAccountsDataProvider.getContactAccountById(13L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_5_subject, body = R.string.email_5_body, createdAt = R.string.email_5_time, ), Email( id = 6L, sender = LocalAccountsDataProvider.getContactAccountById(10L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_6_subject, body = R.string.email_6_body, createdAt = R.string.email_6_time, mailbox = MailboxType.Sent, ), Email( id = 7L, sender = LocalAccountsDataProvider.getContactAccountById(9L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_7_subject, body = R.string.email_7_body, createdAt = R.string.email_7_time, ), Email( id = 8L, sender = LocalAccountsDataProvider.getContactAccountById(13L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_8_subject, body = R.string.email_8_body, createdAt = R.string.email_8_time, ), Email( id = 9L, sender = LocalAccountsDataProvider.getContactAccountById(10L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_9_subject, body = R.string.email_9_body, createdAt = R.string.email_9_time, mailbox = MailboxType.Drafts, ), Email( id = 10L, sender = LocalAccountsDataProvider.getContactAccountById(5L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_10_subject, body = R.string.email_10_body, createdAt = R.string.email_10_time, ), Email( id = 11L, sender = LocalAccountsDataProvider.getContactAccountById(5L), recipients = listOf(LocalAccountsDataProvider.defaultAccount), subject = R.string.email_11_subject, body = R.string.email_11_body, createdAt = R.string.email_11_time, mailbox = MailboxType.Spam, ) ) /** * Get an [Email] with the given [id]. */ fun get(id: Long): Email? { return allEmails.firstOrNull { it.id == id } } val defaultEmail = Email( id = -1, sender = LocalAccountsDataProvider.defaultAccount, ) }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/local/LocalEmailsDataProvider.kt
166451387
/* * 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.data.local import com.example.reply.R import com.example.reply.data.Account /** * An static data store of [Account]s. This includes both [Account]s owned by the current user and * all [Account]s of the current user's contacts. */ object LocalAccountsDataProvider { val defaultAccount = Account(-1, -1, -1, -1, R.drawable.avatar_1) val userAccount = Account( id = 1, firstName = R.string.account_1_first_name, lastName = R.string.account_1_last_name, email = R.string.account_1_email, avatar = R.drawable.avatar_10 ) private val allUserContactAccounts = listOf( Account( id = 4L, firstName = R.string.account_4_first_name, lastName = R.string.account_4_last_name, email = R.string.account_4_email, avatar = R.drawable.avatar_1 ), Account( id = 5L, firstName = R.string.account_5_first_name, lastName = R.string.account_5_last_name, email = R.string.account_5_email, avatar = R.drawable.avatar_3 ), Account( id = 6L, firstName = R.string.account_6_first_name, lastName = R.string.account_6_last_name, email = R.string.account_6_email, avatar = R.drawable.avatar_5 ), Account( id = 7L, firstName = R.string.account_7_first_name, lastName = R.string.account_7_last_name, email = R.string.account_7_email, avatar = R.drawable.avatar_0 ), Account( id = 8L, firstName = R.string.account_8_first_name, lastName = R.string.account_8_last_name, email = R.string.account_8_email, avatar = R.drawable.avatar_7 ), Account( id = 9L, firstName = R.string.account_9_first_name, lastName = R.string.account_9_last_name, email = R.string.account_9_email, avatar = R.drawable.avatar_express ), Account( id = 10L, firstName = R.string.account_10_first_name, lastName = R.string.account_10_last_name, email = R.string.account_10_email, avatar = R.drawable.avatar_2 ), Account( id = 11L, firstName = R.string.account_11_first_name, lastName = R.string.account_11_last_name, email = R.string.account_11_email, avatar = R.drawable.avatar_8 ), Account( id = 12L, firstName = R.string.account_12_first_name, lastName = R.string.account_12_last_name, email = R.string.account_12_email, avatar = R.drawable.avatar_6 ), Account( id = 13L, firstName = R.string.account_13_first_name, lastName = R.string.account_13_last_name, email = R.string.account_13_email, avatar = R.drawable.avatar_4 ) ) /** * Get the contact of the current user with the given [accountId]. */ fun getContactAccountById(accountId: Long): Account { return allUserContactAccounts.firstOrNull { it.id == accountId } ?: allUserContactAccounts.first() } }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/local/LocalAccountsDataProvider.kt
1129306024
/* * 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.data /** * An enum class to define different types of email folders or categories. */ enum class MailboxType { Inbox, Drafts, Sent, Spam }
AndroidLearning/compose-training-reply-app/app/src/main/java/com/example/reply/data/MailboxType.kt
3242064677
/* * 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.racetracker import com.example.racetracker.ui.RaceParticipant import junit.framework.TestCase.assertEquals import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.launch import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import org.junit.Test class RaceParticipantTest { private val raceParticipant = RaceParticipant( name = "Test", maxProgress = 100, progressDelayMillis = 500L, initialProgress = 0, progressIncrement = 1 ) @OptIn(ExperimentalCoroutinesApi::class) @Test fun raceParticipant_RaceStarted_ProgressUpdated() = runTest { val expectedProgress = 1 launch { raceParticipant.run() } advanceTimeBy(raceParticipant.progressDelayMillis) runCurrent() assertEquals(expectedProgress, raceParticipant.currentProgress) } @OptIn(ExperimentalCoroutinesApi::class) @Test fun raceParticipant_RaceFinished_ProgressUpdated() = runTest { launch { raceParticipant.run() } advanceTimeBy(raceParticipant.maxProgress * raceParticipant.progressDelayMillis) runCurrent() assertEquals(100, raceParticipant.currentProgress) } }
AndroidLearning/compose-training-race-tracker/app/src/test/java/com/example/racetracker/RaceParticipantTest.kt
2677409220
/* * 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.racetracker.ui import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.delay /** * This class represents a state holder for race participant. */ class RaceParticipant( val name: String, val maxProgress: Int = 100, val progressDelayMillis: Long = 500L, private val progressIncrement: Int = 1, private val initialProgress: Int = 0 ) { init { require(maxProgress > 0) { "maxProgress=$maxProgress; must be > 0" } require(progressIncrement > 0) { "progressIncrement=$progressIncrement; must be > 0" } } /** * Indicates the race participant's current progress */ var currentProgress by mutableStateOf(initialProgress) private set suspend fun run() { try { while (currentProgress < maxProgress) { delay(progressDelayMillis) currentProgress += progressIncrement } }catch (e:CancellationException){ Log.e("RaceParticipant", "$name: ${e.message}") throw e // Always re-throw CancellationException. } } /** * Regardless of the value of [initialProgress] the reset function will reset the * [currentProgress] to 0 */ fun reset() { currentProgress = 0 } } /** * The Linear progress indicator expects progress value in the range of 0-1. This property * calculate the progress factor to satisfy the indicator requirements. */ val RaceParticipant.progressFactor: Float get() = currentProgress / maxProgress.toFloat()
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/RaceParticipant.kt
2784880172
/* * 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.racetracker.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import com.example.racetracker.R import com.example.racetracker.ui.theme.RaceTrackerTheme import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch @Composable fun RaceTrackerApp() { /** * Note: To survive the configuration changes such as screen rotation, [rememberSaveable] should * be used with custom Saver object. But to keep the example simple, and keep focus on * Coroutines that implementation detail is stripped out. */ val playerOne = remember { RaceParticipant(name = "Player 1", progressIncrement = 1) } val playerTwo = remember { RaceParticipant(name = "Player 2", progressIncrement = 2) } var raceInProgress by remember { mutableStateOf(false) } if (raceInProgress) { LaunchedEffect(playerOne, playerTwo) { coroutineScope { launch { playerOne.run() } launch { playerTwo.run() } } raceInProgress = false } } RaceTrackerScreen( playerOne = playerOne, playerTwo = playerTwo, isRunning = raceInProgress, onRunStateChange = { raceInProgress = it }, modifier = Modifier .statusBarsPadding() .fillMaxSize() .verticalScroll(rememberScrollState()) .safeDrawingPadding() .padding(horizontal = dimensionResource(R.dimen.padding_medium)), ) } @Composable private fun RaceTrackerScreen( playerOne: RaceParticipant, playerTwo: RaceParticipant, isRunning: Boolean, onRunStateChange: (Boolean) -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier, verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(R.string.run_a_race), style = MaterialTheme.typography.headlineSmall, ) Column( modifier = Modifier .fillMaxSize() .padding(dimensionResource(R.dimen.padding_medium)), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { Icon( painter = painterResource(R.drawable.ic_walk), contentDescription = null, modifier = Modifier.padding(dimensionResource(R.dimen.padding_medium)), ) StatusIndicator( participantName = playerOne.name, currentProgress = playerOne.currentProgress, maxProgress = stringResource( R.string.progress_percentage, playerOne.maxProgress ), progressFactor = playerOne.progressFactor, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.size(dimensionResource(R.dimen.padding_large))) StatusIndicator( participantName = playerTwo.name, currentProgress = playerTwo.currentProgress, maxProgress = stringResource( R.string.progress_percentage, playerTwo.maxProgress ), progressFactor = playerTwo.progressFactor, modifier = Modifier.fillMaxWidth(), ) Spacer(modifier = Modifier.size(dimensionResource(R.dimen.padding_large))) RaceControls( isRunning = isRunning, onRunStateChange = onRunStateChange, onReset = { playerOne.reset() playerTwo.reset() onRunStateChange(false) }, modifier = Modifier.fillMaxWidth(), ) } } } @Composable private fun StatusIndicator( participantName: String, currentProgress: Int, maxProgress: String, progressFactor: Float, modifier: Modifier = Modifier ) { Row( modifier = modifier ) { Text( text = participantName, modifier = Modifier.padding(end = dimensionResource(R.dimen.padding_small)) ) Column( verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { LinearProgressIndicator( progress = progressFactor, modifier = Modifier .fillMaxWidth() .height(dimensionResource(R.dimen.progress_indicator_height)) .clip(RoundedCornerShape(dimensionResource(R.dimen.progress_indicator_corner_radius))) ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = stringResource(R.string.progress_percentage, currentProgress), textAlign = TextAlign.Start, modifier = Modifier.weight(1f) ) Text( text = maxProgress, textAlign = TextAlign.End, modifier = Modifier.weight(1f) ) } } } } @Composable private fun RaceControls( onRunStateChange: (Boolean) -> Unit, onReset: () -> Unit, modifier: Modifier = Modifier, isRunning: Boolean = true, ) { Column( modifier = modifier.padding(top = dimensionResource(R.dimen.padding_medium)), verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_medium)) ) { Button( onClick = { onRunStateChange(!isRunning) }, modifier = Modifier.fillMaxWidth(), ) { Text(if (isRunning) stringResource(R.string.pause) else stringResource(R.string.start)) } OutlinedButton( onClick = onReset, modifier = Modifier.fillMaxWidth(), ) { Text(stringResource(R.string.reset)) } } } @Preview(showBackground = true) @Composable fun RaceTrackerAppPreview() { RaceTrackerTheme { RaceTrackerApp() } }
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/RaceTrackerApp.kt
1729704674
/* * 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.racetracker.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFFA23F00) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFFFDBCC) val md_theme_light_onPrimaryContainer = Color(0xFF351000) val md_theme_light_secondary = Color(0xFF76574A) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFFFDBCC) val md_theme_light_onSecondaryContainer = Color(0xFF2C160C) val md_theme_light_tertiary = Color(0xFF665F31) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFEEE4A9) val md_theme_light_onTertiaryContainer = Color(0xFF201C00) 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(0xFFFFFBFF) val md_theme_light_onBackground = Color(0xFF201A18) val md_theme_light_surface = Color(0xFFFFFBFF) val md_theme_light_onSurface = Color(0xFF201A18) val md_theme_light_surfaceVariant = Color(0xFFF4DED5) val md_theme_light_onSurfaceVariant = Color(0xFF52443D) val md_theme_light_outline = Color(0xFF85736C) val md_theme_light_inverseOnSurface = Color(0xFFFBEEE9) val md_theme_light_inverseSurface = Color(0xFF362F2C) val md_theme_light_inversePrimary = Color(0xFFFFB695) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFFA23F00) val md_theme_light_outlineVariant = Color(0xFFD8C2BA) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFFFB695) val md_theme_dark_onPrimary = Color(0xFF571F00) val md_theme_dark_primaryContainer = Color(0xFF7B2F00) val md_theme_dark_onPrimaryContainer = Color(0xFFFFDBCC) val md_theme_dark_secondary = Color(0xFFE6BEAD) val md_theme_dark_onSecondary = Color(0xFF442A1F) val md_theme_dark_secondaryContainer = Color(0xFF5D4034) val md_theme_dark_onSecondaryContainer = Color(0xFFFFDBCC) val md_theme_dark_tertiary = Color(0xFFD1C88F) val md_theme_dark_onTertiary = Color(0xFF363106) val md_theme_dark_tertiaryContainer = Color(0xFF4E471B) val md_theme_dark_onTertiaryContainer = Color(0xFFEEE4A9) 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(0xFF201A18) val md_theme_dark_onBackground = Color(0xFFEDE0DB) val md_theme_dark_surface = Color(0xFF201A18) val md_theme_dark_onSurface = Color(0xFFEDE0DB) val md_theme_dark_surfaceVariant = Color(0xFF52443D) val md_theme_dark_onSurfaceVariant = Color(0xFFD8C2BA) val md_theme_dark_outline = Color(0xFFA08D85) val md_theme_dark_inverseOnSurface = Color(0xFF201A18) val md_theme_dark_inverseSurface = Color(0xFFEDE0DB) val md_theme_dark_inversePrimary = Color(0xFFA23F00) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFFFB695) val md_theme_dark_outlineVariant = Color(0xFF52443D) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/theme/Color.kt
1023910610
/* * 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.racetracker.ui.theme 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.ui.platform.LocalContext private val LightColorScheme = 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 DarkColorScheme = 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 RaceTrackerTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ 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 } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/ui/theme/Theme.kt
191274217
/* * 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.racetracker.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-race-tracker/app/src/main/java/com/example/racetracker/ui/theme/Type.kt
1481981863
/* * 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.racetracker 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.racetracker.ui.RaceTrackerApp import com.example.racetracker.ui.theme.RaceTrackerTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { RaceTrackerTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), ) { RaceTrackerApp() } } } } }
AndroidLearning/compose-training-race-tracker/app/src/main/java/com/example/racetracker/MainActivity.kt
2135823089
package com.example.sqldemo 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.sqldemo", appContext.packageName) } }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/androidTest/java/com/example/sqldemo/ExampleInstrumentedTest.kt
3981903659
package com.example.sqldemo 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/kotlin-sql-basics-app-compose/app/src/test/java/com/example/sqldemo/ExampleUnitTest.kt
855005314
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://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.sqldemo.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/ui/theme/Shape.kt
1293172813
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://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.sqldemo.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/ui/theme/Color.kt
3159954763
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://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.sqldemo.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun SQLDemoTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/ui/theme/Theme.kt
3486927495
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://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.sqldemo.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ )
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/ui/theme/Type.kt
3124629473
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://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.sqldemo import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "email") data class Email( @PrimaryKey(autoGenerate = true) val id: Int, @ColumnInfo(name = "subject") val subject: String, @ColumnInfo(name = "sender") val sender: String, @ColumnInfo(name = "folder") val folder: String, @ColumnInfo(name = "starred") val starred: Boolean, @ColumnInfo(name = "read") val read: Boolean, @ColumnInfo(name = "received") val received: Int )
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/Email.kt
115594876
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://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.sqldemo import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.example.sqldemo.ui.theme.SQLDemoTheme import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GlobalScope.launch { AppDatabase.getDatabase(applicationContext).emailDao().getAll() } setContent { SQLDemoTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Text("The database is ready!") } } } } } }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/MainActivity.kt
507678969
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://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.sqldemo import androidx.room.Dao import androidx.room.Query @Dao interface EmailDao { @Query("SELECT * FROM email") suspend fun getAll(): List<Email> }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/EmailDao.kt
1829968925
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://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.sqldemo import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase @Database(entities = arrayOf(Email::class), version = 1) abstract class AppDatabase: RoomDatabase() { abstract fun emailDao(): EmailDao companion object { @Volatile private var INSTANCE: AppDatabase? = null fun getDatabase( context: Context ): AppDatabase { return INSTANCE ?: synchronized(this) { val instance = Room.databaseBuilder( context, AppDatabase::class.java, "app_database" ) .createFromAsset("database/Email.db") .build() INSTANCE = instance instance } } } }
AndroidLearning/kotlin-sql-basics-app-compose/app/src/main/java/com/example/sqldemo/AppDatabase.kt
1223530751
package com.suhas.activity 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.suhas.activity", appContext.packageName) } }
AndroidLearning/appcomponents/app/src/androidTest/java/com/suhas/activity/ExampleInstrumentedTest.kt
3408039639
package com.suhas.activity 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/appcomponents/app/src/test/java/com/suhas/activity/ExampleUnitTest.kt
168364524
package com.suhas.activity.providers import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.content.Context import android.content.UriMatcher import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteException import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteQueryBuilder import android.net.Uri class MyProvider : ContentProvider() { private var db: SQLiteDatabase? = null companion object { //Defining authority so that other application can access it const val PROVIDER_NAME = "com.suhas.activity.provider" //defining content URI const val URL = "content://$PROVIDER_NAME/users" //prasing the content uri val CONTENT_URI = Uri.parse(URL) const val id = "id" const val name = "name" const val uriCode = 1 var uriMatcher: UriMatcher? = null private val values: HashMap<String, String>? = null //declaring name of Database const val DATABASE_NAME = "UserDB" //declaring table name of the database const val TABLE_NAME = "Users" //declaring database version const val DB_VERSION = 1 //sql Query to create table const val CREATE_DB_TABLE = ("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY AUTOINCREMENT," + "name TEXT NOT NULL);") init { //to match the content uri //every time user access table undercontent provider uriMatcher = UriMatcher(UriMatcher.NO_MATCH) //to access whole table uriMatcher!!.addURI( PROVIDER_NAME, "users", uriCode ) //to acess a particular row //of the table uriMatcher!!.addURI( PROVIDER_NAME, "users/*", uriCode ) } } override fun getType(p0: Uri): String? { return when (uriMatcher!!.match(p0)) { uriCode -> "vnd.android.cursor.dir/users" else -> throw IllegalArgumentException("Unsupported URI: $p0") } } override fun onCreate(): Boolean { val context = context val dbHelper = DatabseHelper(context) db = dbHelper.writableDatabase return db != null } override fun query( p0: Uri, p1: Array<out String>?, p2: String?, p3: Array<out String>?, p4: String? ): Cursor? { var sortOrder = p4 val qb = SQLiteQueryBuilder() qb.tables = TABLE_NAME when (uriMatcher!!.match(p0)) { uriCode -> qb.projectionMap = values else -> throw IllegalArgumentException("UNKNOWN URI $p0") } if (sortOrder == null || sortOrder === "") { sortOrder = id } val c = qb.query(db, p1, p2, p3, null, null, sortOrder) c.setNotificationUri(context!!.contentResolver, p0) return c } override fun insert(p0: Uri, p1: ContentValues?): Uri? { val rowID = db!!.insert(TABLE_NAME, "", p1) if (rowID > 0) { val uri = ContentUris.withAppendedId(CONTENT_URI, rowID) context!!.contentResolver.notifyChange(uri, null) return uri } else throw SQLiteException("Filed to add a record into $p0") } override fun delete(p0: Uri, p1: String?, p2: Array<out String>?): Int { var count = 0 count = when (uriMatcher!!.match(p0)) { uriCode -> db!!.delete(TABLE_NAME, p1, p2) else -> throw IllegalArgumentException("UNKNOWN URI $p0") } context!!.contentResolver.notifyChange(p0, null) return count } override fun update(p0: Uri, p1: ContentValues?, p2: String?, p3: Array<out String>?): Int { var count = 0 count = when (uriMatcher!!.match(p0)) { uriCode -> db!!.update(TABLE_NAME, p1, p2, p3) else -> throw IllegalArgumentException("UNKNOWN URI $p0") } context!!.contentResolver.notifyChange(p0, null) return count } //createing the object of database //to perform query private class DatabseHelper(context: Context?) : SQLiteOpenHelper(context, DATABASE_NAME, null, DB_VERSION) { override fun onCreate(db: SQLiteDatabase) { db.execSQL(CREATE_DB_TABLE) } override fun onUpgrade( db: SQLiteDatabase, oldversion: Int, newVersion: Int ) { //Sql query to drop a table //having similar name db.execSQL("DROP TABLE IF EXISTS $TABLE_NAME") } } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/providers/MyProvider.kt
3484757417
package com.suhas.activity import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.activites.BroadcastReciverExample import com.suhas.activity.activites.ContentResolverExample import com.suhas.activity.activites.LifeCycleActivity import com.suhas.activity.activites.ProviderExample import com.suhas.activity.activites.ServiceExample class Main : AppCompatActivity() { private lateinit var serviceExample: Button private lateinit var activityExample: Button private lateinit var reciverExample: Button private lateinit var providerExmple: Button private lateinit var resolverExmple: Button @SuppressLint("MissingInflatedId") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) serviceExample = findViewById(R.id.service_example) activityExample = findViewById(R.id.activity_example) reciverExample = findViewById(R.id.broadcast_receivers_example) providerExmple = findViewById(R.id.content_providers_example) resolverExmple = findViewById(R.id.content_resolver_example) resolverExmple.setOnClickListener { startActivity(Intent(this@Main, ContentResolverExample::class.java)) } serviceExample.setOnClickListener { startActivity(Intent(this@Main, ServiceExample::class.java)) } activityExample.setOnClickListener { startActivity(Intent(this@Main, LifeCycleActivity::class.java)) } reciverExample.setOnClickListener { startActivity( Intent( this@Main, BroadcastReciverExample::class.java ) ) } providerExmple.setOnClickListener { startActivity(Intent(this@Main, ProviderExample::class.java)) } } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/Main.kt
1381935830
package com.suhas.activity.activites import android.annotation.SuppressLint import android.net.Uri import android.os.Bundle import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R class ContentResolverExample : AppCompatActivity() { val uri = Uri.parse("content://com.suhas.activity.provider/users") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_c_reslover) } @SuppressLint("Range") fun onClickShowDetails() { val resultView = findViewById<View>(R.id.res) as TextView val cursor = contentResolver.query( uri, null, null, null, null ) if (cursor!!.moveToFirst()) { val strBuild = StringBuilder() while (!cursor.isAfterLast) { strBuild.append( """${cursor.getString(cursor.getColumnIndex("id"))}-${ cursor.getString( cursor.getColumnIndex( "name" ) ) } """.trimIndent() ) cursor.moveToNext() } resultView.text = strBuild } else { resultView.text = "No Data Found!" } cursor.close() } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/ContentResolverExample.kt
867738960
package com.suhas.activity.activites import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R /* This Activity Demonstrate Activity LifeCycle and State Changes */ class LifeCycleActivity : AppCompatActivity() { private val tag = "MainActivity" //onCreate() //This is the first callback and called when the activity is first created. override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lifecycle_activity) Log.i(tag, ":-onCreate()") Show("onCreate()") } // onStart() // This callback is called when the activity becomes visible to the user. override fun onStart() { super.onStart() Log.i(tag, ":-onStart()") Show("onStart()") } //onPause() //The paused activity does not receive user input and cannot execute any code and called when the current activity is being paused and the previous activity is being resumed. override fun onPause() { super.onPause() Log.i(tag, ":-onPause()") Show("onPause()") } //onResume() //This is called when the user starts interacting with the application. override fun onResume() { super.onResume() Log.i(tag, ":-onResume()") Show("onResume()") } //onStop() //This callback is called when the activity is no longer visible. override fun onStop() { super.onStop() Log.i(tag, ":-onStop()") Show("onStop()") } //onDestroy() //This callback is called before the activity is destroyed by the system. override fun onDestroy() { super.onDestroy() Log.i(tag, ":-onDestroy()") Show("onDestroy()") } //onRestart() //This callback is called when the activity restarts after stopping it. override fun onRestart() { super.onRestart() Log.i(tag, ":-onRestart() ") Show("onRestart()") } fun Show(msg: String) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show() } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/LifeCycleActivity.kt
464305884
package com.suhas.activity.activites import android.annotation.SuppressLint import android.content.ContentValues import android.content.Context import android.net.Uri import android.os.Bundle import android.view.MotionEvent import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R import com.suhas.activity.providers.MyProvider import java.lang.StringBuilder class ProviderExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_c_provider) } override fun onTouchEvent(event: MotionEvent?): Boolean { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(currentFocus!!.windowToken, 0) return super.onTouchEvent(event) } fun onClickAddDetails(view: View?) { val values = ContentValues() values.put( MyProvider.name, (findViewById<View>(R.id.textName) as EditText).text.toString() ) contentResolver.insert(MyProvider.CONTENT_URI, values) Toast.makeText(baseContext, "New Record Inserted", Toast.LENGTH_LONG).show() } @SuppressLint("Range") fun onClickShowDetails(view: View?) { val resultView = findViewById<View>(R.id.res) as TextView val cursor = contentResolver.query( Uri.parse("content://${MyProvider.PROVIDER_NAME}/users"), null, null, null, null ) if(cursor!!.moveToFirst()){ val strBuild=StringBuilder() while (!cursor.isAfterLast){ strBuild.append("""${cursor.getString(cursor.getColumnIndex("id"))}-${cursor.getString(cursor.getColumnIndex("name"))}""".trimIndent()) cursor.moveToNext() } resultView.text=strBuild }else{ resultView.text="No Records Found" } cursor.close() } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/ProviderExample.kt
2052852695
package com.suhas.activity.activites import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R import com.suhas.activity.services.MyService class ServiceExample : AppCompatActivity() { private var myBoundService: MyService? = null private val serviceConnection = object : ServiceConnection { override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) { myBoundService = (p1 as MyService.MyServiceBinder).getService() } override fun onServiceDisconnected(p0: ComponentName?) { myBoundService = null } } private lateinit var start: Button private lateinit var stop: Button private lateinit var bind: Button private lateinit var unBind: Button private lateinit var reBind: Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lifecycle_service) start = findViewById(R.id.start_service) stop = findViewById(R.id.stop_service) bind = findViewById(R.id.bind_service) unBind = findViewById(R.id.unbind_service) reBind = findViewById(R.id.rebind_service) val i = Intent(baseContext, MyService::class.java) start.setOnClickListener { startService(i) } stop.setOnClickListener { stopService(i) } bind.setOnClickListener { bindService(i, serviceConnection, Context.BIND_AUTO_CREATE) } unBind.setOnClickListener { unbindService(serviceConnection) } reBind.setOnClickListener { bindService(i, serviceConnection, BIND_AUTO_CREATE) } } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/ServiceExample.kt
1614313999
package com.suhas.activity.activites import android.content.Intent import android.content.IntentFilter import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.suhas.activity.R import com.suhas.activity.broadcast.MyReceiver class BroadcastReciverExample : AppCompatActivity() { private val reciver: MyReceiver = MyReceiver() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_reciver_example) val intentFilter = IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED) registerReceiver(reciver, intentFilter) } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/activites/BroadcastReciverExample.kt
3103392116
package com.suhas.activity.broadcast import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast class MyReceiver : BroadcastReceiver() { @SuppressLint("UnsafeProtectedBroadcastReceiver") override fun onReceive(p0: Context?, p1: Intent?) { val isAirplaneModeEnabled = p1?.getBooleanExtra("EXTRA_AIRPLANE_MODE", false) if ((isAirplaneModeEnabled != null) && isAirplaneModeEnabled) { Toast.makeText(p0,"Airplane Mode ON",Toast.LENGTH_SHORT).show() } else { Toast.makeText(p0,"Airplane Mode Off",Toast.LENGTH_SHORT).show() } } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/broadcast/MyReceiver.kt
1950349079
package com.suhas.activity.services import android.app.Service import android.content.Intent import android.os.Binder import android.os.IBinder import android.widget.Toast class MyService : Service() { private val binder = MyServiceBinder() inner class MyServiceBinder : Binder() { fun getService(): MyService { return this@MyService } } override fun onCreate() { super.onCreate() Toast.makeText(this, "Service OnCreate.....", Toast.LENGTH_SHORT).show() } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Toast.makeText(this, "Service Started.....", Toast.LENGTH_SHORT).show() return START_STICKY } override fun onDestroy() { Toast.makeText(this, "Service Destroy.....", Toast.LENGTH_SHORT).show() super.onDestroy() } override fun onBind(p0: Intent?): IBinder { Toast.makeText(this, "Service Bind.....", Toast.LENGTH_SHORT).show() return binder } override fun onRebind(intent: Intent?) { Toast.makeText(this, "Service ReBind.....", Toast.LENGTH_SHORT).show() super.onRebind(intent) } override fun onUnbind(intent: Intent?): Boolean { Toast.makeText(this, "Service UnBind.....", Toast.LENGTH_SHORT).show() return super.onUnbind(intent) } }
AndroidLearning/appcomponents/app/src/main/java/com/suhas/activity/services/MyService.kt
3150789938
/* * 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.woof.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(50.dp), medium = RoundedCornerShape(bottomStart = 16.dp, topEnd = 16.dp) )
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/ui/theme/Shape.kt
3742047819
package com.example.woof.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF006C4C) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFF89F8C7) val md_theme_light_onPrimaryContainer = Color(0xFF002114) val md_theme_light_secondary = Color(0xFF4D6357) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFCFE9D9) val md_theme_light_onSecondaryContainer = Color(0xFF092016) val md_theme_light_tertiary = Color(0xFF3D6373) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFC1E8FB) val md_theme_light_onTertiaryContainer = Color(0xFF001F29) 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(0xFFFBFDF9) val md_theme_light_onBackground = Color(0xFF191C1A) val md_theme_light_surface = Color(0xFFFBFDF9) val md_theme_light_onSurface = Color(0xFF191C1A) val md_theme_light_surfaceVariant = Color(0xFFDBE5DD) val md_theme_light_onSurfaceVariant = Color(0xFF404943) val md_theme_light_outline = Color(0xFF707973) val md_theme_light_inverseOnSurface = Color(0xFFEFF1ED) val md_theme_light_inverseSurface = Color(0xFF2E312F) val md_theme_light_inversePrimary = Color(0xFF6CDBAC) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF006C4C) val md_theme_light_outlineVariant = Color(0xFFBFC9C2) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFF6CDBAC) val md_theme_dark_onPrimary = Color(0xFF003826) val md_theme_dark_primaryContainer = Color(0xFF005138) val md_theme_dark_onPrimaryContainer = Color(0xFF89F8C7) val md_theme_dark_secondary = Color(0xFFB3CCBE) val md_theme_dark_onSecondary = Color(0xFF1F352A) val md_theme_dark_secondaryContainer = Color(0xFF354B40) val md_theme_dark_onSecondaryContainer = Color(0xFFCFE9D9) val md_theme_dark_tertiary = Color(0xFFA5CCDF) val md_theme_dark_onTertiary = Color(0xFF073543) val md_theme_dark_tertiaryContainer = Color(0xFF244C5B) val md_theme_dark_onTertiaryContainer = Color(0xFFC1E8FB) 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(0xFF191C1A) val md_theme_dark_onBackground = Color(0xFFE1E3DF) val md_theme_dark_surface = Color(0xFF191C1A) val md_theme_dark_onSurface = Color(0xFFE1E3DF) val md_theme_dark_surfaceVariant = Color(0xFF404943) val md_theme_dark_onSurfaceVariant = Color(0xFFBFC9C2) val md_theme_dark_outline = Color(0xFF8A938C) val md_theme_dark_inverseOnSurface = Color(0xFF191C1A) val md_theme_dark_inverseSurface = Color(0xFFE1E3DF) val md_theme_dark_inversePrimary = Color(0xFF006C4C) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFF6CDBAC) val md_theme_dark_outlineVariant = Color(0xFF404943) val md_theme_dark_scrim = Color(0xFF000000)
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/ui/theme/Color.kt
4222553654
package com.example.woof.ui.theme import android.app.Activity import android.os.Build import android.view.View 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 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 WoofTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ 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 { setUpEdgeToEdge(view, darkTheme) } } MaterialTheme( colorScheme = colorScheme, shapes = Shapes, typography = Typography, content = content ) } /** * Sets up edge-to-edge for the window of this [view]. The system icon colors are set to either * light or dark depending on whether the [darkTheme] is enabled or not. */ private fun setUpEdgeToEdge(view: View, darkTheme: Boolean) { val window = (view.context as Activity).window WindowCompat.setDecorFitsSystemWindows(window, false) window.statusBarColor = Color.Transparent.toArgb() val navigationBarColor = when { Build.VERSION.SDK_INT >= 29 -> Color.Transparent.toArgb() Build.VERSION.SDK_INT >= 26 -> Color(0xFF, 0xFF, 0xFF, 0x63).toArgb() // Min sdk version for this app is 24, this block is for SDK versions 24 and 25 else -> Color(0x00, 0x00, 0x00, 0x50).toArgb() } window.navigationBarColor = navigationBarColor val controller = WindowCompat.getInsetsController(window, view) controller.isAppearanceLightStatusBars = !darkTheme controller.isAppearanceLightNavigationBars = !darkTheme }
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/ui/theme/Theme.kt
2883482149
/* * 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.woof.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.example.woof.R val AbrilFatface = FontFamily( Font(R.font.abril_fatface_regular) ) val Montserrat = FontFamily( Font(R.font.montserrat_regular), Font(R.font.montserrat_bold, FontWeight.Bold) ) // Set of Material typography styles to start with val Typography = Typography( displayLarge = TextStyle( fontFamily = AbrilFatface, fontWeight = FontWeight.Normal, fontSize = 36.sp ), displayMedium = TextStyle( fontFamily = Montserrat, fontWeight = FontWeight.Bold, fontSize = 20.sp ), labelSmall = TextStyle( fontFamily = Montserrat, fontWeight = FontWeight.Bold, fontSize = 14.sp ), bodyLarge = TextStyle( fontFamily = Montserrat, fontWeight = FontWeight.Normal, fontSize = 14.sp ) )
AndroidLearning/compose-training-woof/app/src/main/java/com/example/woof/ui/theme/Type.kt
3618564123