Лаб 2 вроде конец

This commit is contained in:
Kate 2023-10-25 16:07:52 +04:00
parent b6d335503d
commit 5b71cf1e4b
23 changed files with 93 additions and 117 deletions

Binary file not shown.

View File

@ -9,36 +9,34 @@
<option name="autoReloadType" value="NONE" /> <option name="autoReloadType" value="NONE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="dc3793c7-c725-42e8-8eda-044c95f334c1" name="Changes" comment="Лаб 2 питомцы просто добавлены"> <list default="true" id="dc3793c7-c725-42e8-8eda-044c95f334c1" name="Changes" comment="Лаб 2 выглядит как предварительный конец 2 лабы">
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt" afterDir="false" />
<change afterPath="$PROJECT_DIR$/app/src/main/res/drawable/avatar.jpg" afterDir="false" />
<change afterPath="$PROJECT_DIR$/report/~$Lab1.docx" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.bin" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.bin" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.lock" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/executionHistory/executionHistory.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.bin" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.bin" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.lock" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/fileHashes.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/resourceHashesCache.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/resourceHashesCache.bin" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/8.0/fileHashes/resourceHashesCache.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/8.0/fileHashes/resourceHashesCache.bin" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/buildOutputCleanup.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/buildOutputCleanup/buildOutputCleanup.lock" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/buildOutputCleanup.lock" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/buildOutputCleanup/buildOutputCleanup.lock" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/buildOutputCleanup/outputFiles.bin" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/buildOutputCleanup/outputFiles.bin" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.gradle/file-system.probe" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/file-system.probe" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.gradle/file-system.probe" beforeDir="false" afterPath="$PROJECT_DIR$/.gradle/file-system.probe" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/build.gradle.kts" beforeDir="false" afterPath="$PROJECT_DIR$/app/build.gradle.kts" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/build.gradle.kts" beforeDir="false" afterPath="$PROJECT_DIR$/app/build.gradle.kts" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/CreatePet.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/EditPet.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Home.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Home.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Home.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Home.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Login.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Login.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/PlayPet.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Profile.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Profile.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Profile.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/Profile.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/MyPage.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/Screen.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/composeui/navigation/Screen.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/PetList.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/Pet.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/Pet.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/StudentView.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/StudentView.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/User.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/model/User.kt" afterDir="false" /> <change beforePath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/java/com/example/pmuapp/models/user/composeui/UserList.kt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/app/src/main/res/values/strings.xml" beforeDir="false" afterPath="$PROJECT_DIR$/app/src/main/res/values/strings.xml" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" /> <option name="LAST_RESOLUTION" value="IGNORE" />
</component> </component>
<component name="ExecutionTargetManager" SELECTED_TARGET="device_and_snapshot_combo_box_target[adb-RF8N601QWVE-2InjWs._adb-tls-connect._tcp]" /> <component name="ExecutionTargetManager" SELECTED_TARGET="device_and_snapshot_combo_box_target[RF8N601QWVE]" />
<component name="ExternalProjectsData"> <component name="ExternalProjectsData">
<projectState path="$PROJECT_DIR$"> <projectState path="$PROJECT_DIR$">
<ProjectState /> <ProjectState />
@ -136,6 +134,9 @@
<key name="MoveFile.RECENT_KEYS"> <key name="MoveFile.RECENT_KEYS">
<recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\java\com\example\pmuapp\composeui" /> <recent name="C:\Users\Kate\AndroidStudioProjects\Ihonkina_PIbd-31_PMU\app\src\main\java\com\example\pmuapp\composeui" />
</key> </key>
<key name="CreateKotlinClassDialog.RecentsKey">
<recent name="com.example.pmuapp.composeui" />
</key>
<key name="MoveKotlinTopLevelDeclarationsDialog.RECENTS_KEY"> <key name="MoveKotlinTopLevelDeclarationsDialog.RECENTS_KEY">
<recent name="com.example.pmuapp.composeui" /> <recent name="com.example.pmuapp.composeui" />
</key> </key>
@ -255,7 +256,21 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1697054812374</updated> <updated>1697054812374</updated>
</task> </task>
<option name="localTasksCounter" value="6" /> <task id="LOCAL-00006" summary="Лаб 2 выглядит как предварительный конец 2 лабы">
<created>1697086817058</created>
<option name="number" value="00006" />
<option name="presentableId" value="LOCAL-00006" />
<option name="project" value="LOCAL" />
<updated>1697086817058</updated>
</task>
<task id="LOCAL-00007" summary="Лаб 2 выглядит как предварительный конец 2 лабы">
<created>1697086828529</created>
<option name="number" value="00007" />
<option name="presentableId" value="LOCAL-00007" />
<option name="project" value="LOCAL" />
<updated>1697086828529</updated>
</task>
<option name="localTasksCounter" value="8" />
<servers /> <servers />
</component> </component>
<component name="Vcs.Log.Tabs.Properties"> <component name="Vcs.Log.Tabs.Properties">
@ -288,6 +303,7 @@
<MESSAGE value="Лаб 2 начало" /> <MESSAGE value="Лаб 2 начало" />
<MESSAGE value="Лаб 2 нало работы с пользователем" /> <MESSAGE value="Лаб 2 нало работы с пользователем" />
<MESSAGE value="Лаб 2 питомцы просто добавлены" /> <MESSAGE value="Лаб 2 питомцы просто добавлены" />
<option name="LAST_COMMIT_MESSAGE" value="Лаб 2 питомцы просто добавлены" /> <MESSAGE value="Лаб 2 выглядит как предварительный конец 2 лабы" />
<option name="LAST_COMMIT_MESSAGE" value="Лаб 2 выглядит как предварительный конец 2 лабы" />
</component> </component>
</project> </project>

View File

@ -52,7 +52,6 @@ android {
dependencies { dependencies {
implementation ("io.coil-kt:coil-compose:1.4.0") implementation ("io.coil-kt:coil-compose:1.4.0")
implementation("androidx.core:core-ktx:1.9.0") implementation("androidx.core:core-ktx:1.9.0")
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2") implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.2")
implementation("androidx.activity:activity-compose:1.7.2") implementation("androidx.activity:activity-compose:1.7.2")

View File

@ -26,7 +26,6 @@ fun CreatePet(navController: NavController, onSaveClick: (Pet) -> Unit) {
.fillMaxSize() .fillMaxSize()
.padding(16.dp) .padding(16.dp)
) { ) {
// Отображение изображений для выбора
val imageIds = intArrayOf( val imageIds = intArrayOf(
R.drawable.pet1, R.drawable.pet1,
R.drawable.pet2, R.drawable.pet2,
@ -59,7 +58,6 @@ fun CreatePet(navController: NavController, onSaveClick: (Pet) -> Unit) {
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
// Поле для ввода имени питомца
TextField( TextField(
value = petName, value = petName,
onValueChange = { petName = it }, onValueChange = { petName = it },
@ -69,7 +67,6 @@ fun CreatePet(navController: NavController, onSaveClick: (Pet) -> Unit) {
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
// Кнопка "Сохранить"
Button( Button(
onClick = { onClick = {
if (petName.isNotEmpty()) { if (petName.isNotEmpty()) {
@ -78,7 +75,6 @@ fun CreatePet(navController: NavController, onSaveClick: (Pet) -> Unit) {
petName = "" petName = ""
selectedImage = R.drawable.pet1 selectedImage = R.drawable.pet1
// Навигация назад на предыдущую страницу
navController.popBackStack() navController.popBackStack()
} }
}, },

View File

@ -49,7 +49,6 @@ fun EditPet(navController: NavController ,authViewModel: AuthViewModel, petViewM
.padding(10.dp), .padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
// Отображение изображения (здесь предполагается, что у вас есть доступ к `availablePetImages` по индексу)
val imageResId = pet?.imageResId ?: 0 val imageResId = pet?.imageResId ?: 0
Image( Image(
painter = painterResource(id = imageResId), painter = painterResource(id = imageResId),
@ -59,7 +58,6 @@ fun EditPet(navController: NavController ,authViewModel: AuthViewModel, petViewM
.height(200.dp) .height(200.dp)
) )
// Поле ввода имени
OutlinedTextField( OutlinedTextField(
value = petName, value = petName,
onValueChange = { petName = it }, onValueChange = { petName = it },
@ -69,14 +67,12 @@ fun EditPet(navController: NavController ,authViewModel: AuthViewModel, petViewM
.padding(top = 8.dp) .padding(top = 8.dp)
) )
// Текст "Заметка о питомце"
Text( Text(
text = "Заметка о питомце", text = "Заметка о питомце",
style = TextStyle(fontSize = 16.sp), style = TextStyle(fontSize = 16.sp),
modifier = Modifier.padding(top = 8.dp) modifier = Modifier.padding(top = 8.dp)
) )
// Поле ввода заметок
TextField( TextField(
value = petNotes, value = petNotes,
onValueChange = { petNotes = it }, onValueChange = { petNotes = it },
@ -84,27 +80,23 @@ fun EditPet(navController: NavController ,authViewModel: AuthViewModel, petViewM
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(top = 8.dp) .padding(top = 8.dp)
.heightIn(max = 200.dp) // Заметка будет растянута до конца экрана .heightIn(max = 200.dp)
.padding(16.dp), .padding(16.dp),
readOnly = false // Сделаем его доступным для редактирования readOnly = false
) )
Spacer(modifier = Modifier.weight(1f)) // Заполнитель для размещения кнопки внизу Spacer(modifier = Modifier.weight(1f))
// Кнопка "Изменить"
// Кнопка "Сохранить"
val editedPetId = Screen.PlayPet.route.replace("{id}", pet?.id.toString()) val editedPetId = Screen.PlayPet.route.replace("{id}", pet?.id.toString())
Button( Button(
onClick = { onClick = {
// Создаем обновленную версию питомца с введенными данными
val updatedPet = pet?.copy(name = petName, notes = petNotes) ?: return@Button val updatedPet = pet?.copy(name = petName, notes = petNotes) ?: return@Button
// Вызываем функцию для обновления питомца в вашей ViewModel (в данном случае, в petViewModel)
petViewModel.updatePet(updatedPet) petViewModel.updatePet(updatedPet)
userViewModel.updatePetOnUser(authViewModel.currentUser?.id ?: -1, updatedPet) userViewModel.updatePetOnUser(authViewModel.currentUser?.id ?: -1, updatedPet)
authViewModel.currentUser=userViewModel.getUser(authViewModel.currentUser?.id ?: -1) authViewModel.currentUser=userViewModel.getUser(authViewModel.currentUser?.id ?: -1)
// Дополнительные действия после обновления, например, переход на другой экран
val petId = Screen.EditPet.route.replace("{id}", pet.id.toString()) val petId = Screen.EditPet.route.replace("{id}", pet.id.toString())
navController?.navigate(editedPetId) navController?.navigate(editedPetId)
}, },

View File

@ -25,10 +25,8 @@ fun Home(navController: NavController, authViewModel: AuthViewModel, petViewMode
verticalArrangement = Arrangement.Center, verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
// Add a button to navigate to the "Create Pet" screen
Button( Button(
onClick = { onClick = {
// При нажатии кнопки, перейдите на экран создания питомца (CreatePet)
navController.navigate(Screen.CreatePet.route) navController.navigate(Screen.CreatePet.route)
} }
) { ) {
@ -36,7 +34,6 @@ fun Home(navController: NavController, authViewModel: AuthViewModel, petViewMode
} }
Spacer(modifier = Modifier.height(16.dp)) Spacer(modifier = Modifier.height(16.dp))
// Вывод списка питомцев
PetList(navController,authViewModel, petViewModel, userViewModel, authViewModel.currentUser?.id ?: -1) PetList(navController,authViewModel, petViewModel, userViewModel, authViewModel.currentUser?.id ?: -1)
} }

View File

@ -4,6 +4,7 @@ import android.content.Intent
import android.content.res.Configuration import android.content.res.Configuration
import android.net.Uri import android.net.Uri
import android.widget.TextView import android.widget.TextView
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@ -22,6 +23,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
@ -44,11 +46,12 @@ import com.example.pmuapp.ui.theme.PMUappTheme
fun Login( fun Login(
navController: NavHostController, navController: NavHostController,
authViewModel: AuthViewModel, authViewModel: AuthViewModel,
users: List<User> // Используйте ViewModel как параметр users: List<User>
) { ) {
var username by remember { mutableStateOf("") } var username by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") } var password by remember { mutableStateOf("") }
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
@ -75,7 +78,7 @@ fun Login(
.padding(bottom = 16.dp) .padding(bottom = 16.dp)
) )
Spacer(modifier = Modifier.height(16.dp)) // Промежуток Spacer(modifier = Modifier.height(16.dp))
Button( Button(
onClick = { onClick = {
@ -91,19 +94,11 @@ fun Login(
) { ) {
Text("Login") Text("Login")
} }
} }
} }
//@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
//@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
//@Composable
//fun LoginPreview() {
// PMUappTheme {
// Surface(
// color = MaterialTheme.colorScheme.background
// ) {
// Login()
// }
// }
//}

View File

@ -41,7 +41,6 @@ fun PlayPet(navController: NavController,authViewModel: AuthViewModel, petViewMo
.padding(10.dp), .padding(10.dp),
horizontalAlignment = Alignment.CenterHorizontally horizontalAlignment = Alignment.CenterHorizontally
) { ) {
// Отображение изображения (здесь предполагается, что у вас есть доступ к `availablePetImages` по индексу)
val imageResId = pet?.imageResId ?: 0 val imageResId = pet?.imageResId ?: 0
Image( Image(
painter = painterResource(id = imageResId), painter = painterResource(id = imageResId),
@ -51,42 +50,38 @@ fun PlayPet(navController: NavController,authViewModel: AuthViewModel, petViewMo
.height(200.dp) .height(200.dp)
) )
// Отображение имени
Text( Text(
text = pet?.name ?: "", text = pet?.name ?: "",
style = TextStyle(fontWeight = FontWeight.Bold, fontSize = 24.sp), style = TextStyle(fontWeight = FontWeight.Bold, fontSize = 24.sp),
modifier = Modifier.padding(top = 8.dp) modifier = Modifier.padding(top = 8.dp)
) )
// Текст "Заметка о питомце"
Text( Text(
text = "Заметка о питомце", text = "Заметка о питомце",
style = TextStyle(fontSize = 16.sp), style = TextStyle(fontSize = 16.sp),
modifier = Modifier.padding(top = 8.dp) modifier = Modifier.padding(top = 8.dp)
) )
// Отображение заметок
TextField( TextField(
value = pet?.notes ?: "", value = pet?.notes ?: "",
onValueChange = { /* Обработка изменения текста, если необходимо */ }, onValueChange = { },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.padding(top = 8.dp) .padding(top = 8.dp)
.heightIn(max = 200.dp) // Заметка будет растянута до конца экрана .heightIn(max = 200.dp)
.padding(16.dp), .padding(16.dp),
readOnly = true readOnly = true
) )
Spacer(modifier = Modifier.weight(1f)) // Заполнитель для размещения кнопки внизу Spacer(modifier = Modifier.weight(1f))
val petId = Screen.EditPet.route.replace("{id}", pet?.id.toString()) val petId = Screen.EditPet.route.replace("{id}", pet?.id.toString())
// Кнопка "Изменить"
Button( Button(
onClick = { onClick = {
// Перейти на страницу "играть" с передачей petId как аргумент
navController?.navigate(petId) navController?.navigate(petId)
// Обработка нажатия кнопки "Изменить"
}, },
modifier = Modifier.padding(16.dp) modifier = Modifier.padding(16.dp)
) { ) {

View File

@ -2,34 +2,46 @@ package com.example.pmuapp.composeui
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.net.Uri import android.net.Uri
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.activity.compose.BackHandler
import androidx.activity.compose.LocalOnBackPressedDispatcherOwner
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.TextField import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import coil.compose.rememberImagePainter import coil.compose.rememberImagePainter
import com.example.pmuapp.composeui.navigation.Screen
import com.example.pmuapp.models.user.model.User import com.example.pmuapp.models.user.model.User
import kotlinx.coroutines.flow.callbackFlow
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("RememberReturnType") @SuppressLint("RememberReturnType")
@Composable @Composable
fun Profile(currentUser: User?, onSaveClick: (User) -> Unit) { fun Profile(navController: NavController,currentUser: User?, onSaveClick: (User) -> Unit) {
val nameState = remember { mutableStateOf(currentUser?.name.orEmpty()) } val nameState = remember { mutableStateOf(currentUser?.name.orEmpty()) }
val loginState = remember { mutableStateOf(currentUser?.login.orEmpty()) } val loginState = remember { mutableStateOf(currentUser?.login.orEmpty()) }
val passwordState = remember { mutableStateOf(currentUser?.password.orEmpty()) } val passwordState = remember { mutableStateOf(currentUser?.password.orEmpty()) }
Column( Column(
modifier = Modifier modifier = Modifier
.fillMaxSize() .fillMaxSize()
@ -45,21 +57,16 @@ fun Profile(currentUser: User?, onSaveClick: (User) -> Unit) {
) )
} }
// State to hold the selected image URI
val selectedImageUri = remember { mutableStateOf<Uri?>(null) } val selectedImageUri = remember { mutableStateOf<Uri?>(null) }
// Create an ActivityResultLauncher to handle image selection
val imagePickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { result: Uri? -> val imagePickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { result: Uri? ->
result?.let { uri -> result?.let { uri ->
selectedImageUri.value = uri selectedImageUri.value = uri
} }
} }
// Button to open the image picker
Button( Button(
onClick = { onClick = {
// Request permission to access the device's storage
// Open the image picker
imagePickerLauncher.launch("image/*") imagePickerLauncher.launch("image/*")
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
@ -102,13 +109,23 @@ fun Profile(currentUser: User?, onSaveClick: (User) -> Unit) {
loginState.value, loginState.value,
passwordState.value, passwordState.value,
currentUser?.petId ?: emptyList(), currentUser?.petId ?: emptyList(),
selectedImageUri.value?.toString() ?: "", // Use the selected image URI selectedImageUri.value?.toString() ?: "",
) )
onSaveClick(updatedUser) // Вызывает функцию updateUser в UserViewModel onSaveClick(updatedUser)
}, },
modifier = Modifier.fillMaxWidth() modifier = Modifier.fillMaxWidth()
) { ) {
Text("Сохранить") Text("Сохранить")
} }
Button(
onClick = {
navController.navigate(Screen.Login.route)
},
modifier = Modifier.fillMaxWidth()
) {
Text("Выйти")
}
} }
} }

View File

@ -69,7 +69,6 @@ fun Topbar(
if (currentScreen == Screen.PlayPet) { if (currentScreen == Screen.PlayPet) {
IconButton( IconButton(
onClick = { onClick = {
// Перейти на главный экран
navController.navigate(Screen.Home.route) navController.navigate(Screen.Home.route)
} }
) { ) {
@ -79,7 +78,7 @@ fun Topbar(
tint = MaterialTheme.colorScheme.onPrimary tint = MaterialTheme.colorScheme.onPrimary
) )
} }
} else if ( } else if (
navController.previousBackStackEntry != null navController.previousBackStackEntry != null
&& (currentScreen == null || !currentScreen.showInBottomBar) && (currentScreen == null || !currentScreen.showInBottomBar)
) { ) {
@ -126,9 +125,9 @@ fun Navbar(
fun NavHost( fun NavHost(
navController: NavHostController, navController: NavHostController,
innerPadding: PaddingValues, innerPadding: PaddingValues,
authViewModel: AuthViewModel, // Передайте AuthViewModel как параметр authViewModel: AuthViewModel,
userViewModel: UserViewModel, userViewModel: UserViewModel,
petViewModel: PetViewModel// Передайте UserViewModel как параметр petViewModel: PetViewModel
) { ) {
NavHost( NavHost(
navController = navController, navController = navController,
@ -141,16 +140,15 @@ petViewModel: PetViewModel// Передайте UserViewModel как парам
composable(Screen.Profile.route) { composable(Screen.Profile.route) {
val currentUser = authViewModel.currentUser ?: userViewModel.getUsers().firstOrNull() val currentUser = authViewModel.currentUser ?: userViewModel.getUsers().firstOrNull()
if (currentUser != null) { if (currentUser != null) {
Profile( Profile(navController,
currentUser = currentUser, currentUser = currentUser,
onSaveClick = { updatedUser -> onSaveClick = {updatedUser ->
userViewModel.updateUser(updatedUser) userViewModel.updateUser(updatedUser)
authViewModel.currentUser = updatedUser authViewModel.currentUser = updatedUser
navController.navigate(Screen.Profile.route) navController.navigate(Screen.Profile.route)
} }
) )
} else { } else {
// Обработка случая, если currentUser отсутствует как в AuthViewModel, так и в UserViewModel
} }
} }
@ -174,7 +172,7 @@ petViewModel: PetViewModel// Передайте UserViewModel как парам
val userId = backStackEntry.arguments?.getInt("id") ?: -1 val userId = backStackEntry.arguments?.getInt("id") ?: -1
Box( Box(
contentAlignment = Alignment.TopCenter, // Центрировать содержимое по горизонтали и сверху contentAlignment = Alignment.TopCenter,
modifier = Modifier.fillMaxSize() modifier = Modifier.fillMaxSize()
) { ) {
PetList(navController,authViewModel, petViewModel, userViewModel, userId) PetList(navController,authViewModel, petViewModel, userViewModel, userId)
@ -200,12 +198,13 @@ petViewModel: PetViewModel// Передайте UserViewModel как парам
} }
} }
@RequiresApi(Build.VERSION_CODES.O)
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun MainNavbar() { fun MainNavbar() {
val navController = rememberNavController() val navController = rememberNavController()
val authViewModel = remember { AuthViewModel() } val authViewModel = remember { AuthViewModel() }
val userViewModel =remember {UserViewModel() }// Создайте экземпляр AuthViewModel val userViewModel =remember {UserViewModel() }
val petViewModel = remember {PetViewModel()} val petViewModel = remember {PetViewModel()}
val navBackStackEntry by navController.currentBackStackEntryAsState() val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination val currentDestination = navBackStackEntry?.destination
@ -225,15 +224,15 @@ fun MainNavbar() {
} }
} }
@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO) //@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) //@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable //@Composable
fun MainNavbarPreview() { //fun MainNavbarPreview() {
PMUappTheme { // PMUappTheme {
Surface( // Surface(
color = MaterialTheme.colorScheme.background // color = MaterialTheme.colorScheme.background
) { // ) {
MainNavbar() // MainNavbar()
} // }
} // }
} //}

View File

@ -41,12 +41,11 @@ fun PetList(navController: NavController, authViewModel: AuthViewModel, petViewM
var pets = currentUser.petId var pets = currentUser.petId
LazyColumn( LazyColumn(
verticalArrangement = Arrangement.Center, // Центрировать элементы по вертикали verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally // Центрировать элементы по горизонтали horizontalAlignment = Alignment.CenterHorizontally
) { ) {
if (userId != authViewModel.currentUser?.id ?: -1) { if (userId != authViewModel.currentUser?.id ?: -1) {
item { item {
// Добавляем большой текст с именем пользователя
Text( Text(
text = currentUser?.name + " (" + currentUser.login + ")", text = currentUser?.name + " (" + currentUser.login + ")",
style = TextStyle( style = TextStyle(
@ -83,18 +82,14 @@ fun PetList(navController: NavController, authViewModel: AuthViewModel, petViewM
val petId = Screen.PlayPet.route.replace("{id}", pet.id.toString()) val petId = Screen.PlayPet.route.replace("{id}", pet.id.toString())
Button( Button(
onClick = { onClick = {
// Перейти на страницу "играть" с передачей petId как аргумент
navController?.navigate(petId) navController?.navigate(petId)
}, },
// modifier = Modifier.fillMaxWidth()
) { ) {
Text("Играть") Text("Играть")
} }
// Кнопка удаления питомца
IconButton( IconButton(
onClick = { onClick = {
// Вызывает функцию удаления питомца из PetViewModel
petViewModel.deletePet(pet) petViewModel.deletePet(pet)
userViewModel.deletePet( userViewModel.deletePet(
currentUser?.id currentUser?.id

View File

@ -47,16 +47,3 @@ fun StudentView(user: User) {
) )
} }
} }
//@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
//@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
//@Composable
//fun StudentViewPreview() {
// PMUappTheme {
// Surface(
// color = MaterialTheme.colorScheme.background
// ) {
// StudentView(id = 0)
// }
// }
//}

View File

@ -39,15 +39,3 @@ fun UserList(navController: NavController?,
} }
} }
//@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
//@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
//@Composable
//fun StudentListPreview() {
// PMUappTheme {
// Surface(
// color = MaterialTheme.colorScheme.background
// ) {
// UserList(navController = null)
// }
// }
//}

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

Binary file not shown.