Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Homework/activity 03 #151

Open
wants to merge 3 commits into
base: homework/activity_03
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,5 @@ dependencies {
implementation 'androidx.activity:activity-ktx:1.9.0'
implementation 'androidx.fragment:fragment-ktx:1.7.1'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'androidx.activity:activity:1.9.3'
}
8 changes: 7 additions & 1 deletion app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<uses-permission
android:name="android.permission.CAMERA"
tools:ignore="PermissionImpliesUnsupportedChromeOsHardware" />

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
Expand All @@ -12,7 +16,9 @@
android:supportsRtl="true"
android:theme="@style/Theme.Activities"
tools:targetApi="31">

<activity
android:name=".FillFormActivity"
android:exported="false" />
<activity
android:name=".EditProfileActivity"
android:exported="true">
Expand Down
133 changes: 131 additions & 2 deletions app/src/main/java/otus/gpb/homework/activities/EditProfileActivity.kt
Original file line number Diff line number Diff line change
@@ -1,20 +1,66 @@
package otus.gpb.homework.activities

import android.Manifest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat

class EditProfileActivity : AppCompatActivity() {

private lateinit var imageView: ImageView
private lateinit var firstNameTextView: TextView
private lateinit var lastNameTextView: TextView
private lateinit var ageTextView: TextView
private var imageUri: Uri? = null

private val pickImageLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
uri?.let {
imageUri = it
populateImage(it)
}
}

private val formActivityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val data = result.data
if (data != null) {
firstNameTextView.text = data.getStringExtra("firstName")
lastNameTextView.text = data.getStringExtra("lastName")
ageTextView.text = data.getStringExtra("age")
}
}
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_profile)

imageView = findViewById(R.id.imageview_photo)
firstNameTextView = findViewById(R.id.textview_name)
lastNameTextView = findViewById(R.id.textview_surname)
ageTextView = findViewById(R.id.textview_age)

imageView.setOnClickListener {
showImageOptionsDialog()
}

findViewById<Button>(R.id.button4).setOnClickListener {
val intent = Intent(this, FillFormActivity::class.java)
formActivityLauncher.launch(intent)
}

findViewById<Toolbar>(R.id.toolbar).apply {
inflateMenu(R.menu.menu)
Expand All @@ -30,6 +76,80 @@ class EditProfileActivity : AppCompatActivity() {
}
}

// AlertDialog с выбором действий
private fun showImageOptionsDialog() {
val options = arrayOf("Сделать фото", "Выбрать фото")
AlertDialog.Builder(this)
.setTitle("Выбор действия")
.setItems(options) { dialog, which ->
when (which) {
0 -> requestCameraPermission()
1 -> pickImageLauncher.launch("image/*")
}
}
.show()
}

// Запрос разрешения на камеру
private fun requestCameraPermission() {
when {
ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> {
imageView.setImageResource(R.drawable.cat)
}
shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) -> {
showRationaleDialog()
}
else -> {
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
}
}
}

// Rationale Dialog
private fun showRationaleDialog() {
AlertDialog.Builder(this)
.setTitle("Доступ к камере")
.setMessage("Чтобы сделать фото требуется доступ к камере.")
.setPositiveButton("Дать доступ") { dialog, _ ->
cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
dialog.dismiss()
}
.setNegativeButton("Отмена") { dialog, _ ->
dialog.dismiss()
}
.show()
}

// Диалог для перехода в настройки
private fun showSettingsDialog() {
AlertDialog.Builder(this)
.setTitle("Необходим доступ к камере")
.setMessage("Разрешение камеры отключено. Пожалуйста, включите его в настройках.")
.setPositiveButton("Открыть настройки") { dialog, _ ->
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
data = Uri.fromParts("package", packageName, null)
}
startActivity(intent)
dialog.dismiss()
}
.show()
}

// Запуск разрешения через ResultApi
private val cameraPermissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
if (isGranted) {
imageView.setImageResource(R.drawable.cat)
} else {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
showRationaleDialog()
} else {
showSettingsDialog()
}
}
}

/**
* Используйте этот метод чтобы отобразить картинку полученную из медиатеки в ImageView
*/
Expand All @@ -39,6 +159,15 @@ class EditProfileActivity : AppCompatActivity() {
}

private fun openSenderApp() {
TODO("В качестве реализации метода отправьте неявный Intent чтобы поделиться профилем. В качестве extras передайте заполненные строки и картинку")
val telegramIntent = Intent(Intent.ACTION_SEND).apply {
type = "image/*"
`package` = "org.telegram.messenger"
putExtra(Intent.EXTRA_STREAM, imageUri)
putExtra(
Intent.EXTRA_TEXT,
"Имя: ${firstNameTextView.text}\nФамилия: ${lastNameTextView.text}\nВозраст: ${ageTextView.text}"
)
}
startActivity(telegramIntent)
}
}
50 changes: 50 additions & 0 deletions app/src/main/java/otus/gpb/homework/activities/FillFormActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package otus.gpb.homework.activities

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class FillFormActivity : AppCompatActivity() {

private lateinit var firstNameEditText: EditText
private lateinit var lastNameEditText: EditText
private lateinit var ageEditText: EditText
private lateinit var applyButton: Button

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_fill_form)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

firstNameEditText = findViewById(R.id.editText_firstName)
lastNameEditText = findViewById(R.id.editText_lastName)
ageEditText = findViewById(R.id.editText_age)
applyButton = findViewById(R.id.button_apply)

applyButton.setOnClickListener {
val firstName = firstNameEditText.text.toString()
val lastName = lastNameEditText.text.toString()
val age = ageEditText.text.toString()

val resultIntent = Intent().apply {
putExtra("firstName", firstName)
putExtra("lastName", lastName)
putExtra("age", age)
}

setResult(Activity.RESULT_OK, resultIntent)
finish()
}
}
}
56 changes: 56 additions & 0 deletions app/src/main/res/layout/activity_fill_form.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FillFormActivity">

<EditText
android:id="@+id/editText_firstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp"
android:hint="Имя"
android:textSize="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/editText_lastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:hint="Фамилия"
android:textSize="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_firstName" />

<EditText
android:id="@+id/editText_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:hint="Возраст"
android:textSize="30dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_lastName" />

<Button
android:id="@+id/button_apply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="120dp"
android:text="Применить"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText_age" />

</androidx.constraintlayout.widget.ConstraintLayout>