Skip to content
Closed
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
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Activity #3

### Задание #1
В классе **EditProfileActivity** по клику на `ImageView` с `id=imageview_photo` покажите Alert Dialog с выбором действия. Используйте реализацию диалога указанную в [примере](https://material.io/components/dialogs/android#simple-dialog), в качестве элементов массива добавьте элементы “Сделать фото” и “Выбрать фото”

По клику на кнопку Сделать фото запросите у пользователя Runtime Permission на использование камеры. Обработайте следующие возможные сценарии:

1. Пользователя выдал разрешение на использование камеры → отобразите в ImageView ресурс `R.drawable.cat`
2. Пользователь не разрешил использовать камеру первый раз → ничего не делаем
3. Пользователь еще раз запросил разрешение на использование камеры после отмены → покажите Rationale Dialog, и объясните зачем вам камера

В качестве реализации Rationale Dialog используйте [простой Alert Dialog](https://material.io/components/dialogs/android#alert-dialog) с двумя кнопками: “Дать доступ” и “Отмена”. По клику на кнопку “Дать доступ” повторно запросите разрешение, по клику на кнопку “Отмена” закройте диалоговое окно

4. Пользователь повторно запретил использовать камеру → Покажите диалоговое окно с одной кнопкой → “Открыть настройки”. По клику на кнопку отправьте пользователя в настройки приложения, с возможностью поменять разрешение

> 💡 В этом задании вам не нужно использовать какое либо кеширование/флаги и прочее. Реализуйте все с использованием ResultApi и методов Activity

### Задание #2
По клику на кнопку “Выбрать фото” откройте экран выбора фото из галлереи, после того как вы получите URI фотографии в `ActivityResultCallback` вызовите метод `populateImage`, чтобы отобразить полученную фотографию в ImageView

> 💡 Используйте готовый контракт из класса `ActivityResultContracts` для открытия пикера медиафайлов

<img src="art/Untitled.png" width="720">

### Задание #3
1. Создайте класс-наследник Activity **FillFormActivity** и добавьте в нее 3 EditText для ввода имени, фамилии и возраста, и кнопку “Применить”
2. В **EditProfileActivity** по клику на кнопку “Редактировать профиль” откройте **FillFormActivity** с запросом результата, используя ResultApi
3. По нажатию на кнопку “Применить” на **FillFormActivity** заберите введенный текст из 3 полей и отправьте результат на запустившую ее Activity, тоесть на **EditProfileActivity**
4. В **EditProfileActivity** обработайте полученный результат и отобразите контент в соответствующих TextView
5. Реализуйте функцию `openSenderApp` так, чтобы она отправляла явный интент в Telegram, в качестве extras отправьте картинку полученную из галлереи и контент TextView

<img src="art/Untitled%201.png" width="720">
8 changes: 6 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ detekt {

tasks.named("detekt").configure {
reports {
txt.required.set(true)
html.required.set(false)
txt.required.set(false)
html.required.set(true)
md.required.set(false)
xml.required.set(false)
sarif.required.set(false)
Expand All @@ -52,4 +52,8 @@ dependencies {
implementation 'androidx.core:core-ktx:1.8.0'
implementation 'androidx.appcompat:appcompat:1.5.0'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.activity:activity-ktx:1.5.1'
implementation 'androidx.fragment:fragment-ktx:1.5.2'
implementation 'com.squareup.picasso:picasso:2.71828'
}
19 changes: 17 additions & 2 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="otus.gpb.homework.activities">

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

<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
Expand All @@ -12,6 +13,20 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Activities"
tools:targetApi="31" />
tools:targetApi="31">

<activity
android:name=".EditProfileActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SecondActivity"
android:exported="false">
</activity>
</application>

</manifest>
158 changes: 158 additions & 0 deletions app/src/main/java/otus/gpb/homework/activities/EditProfileActivity.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
package otus.gpb.homework.activities

import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import android.content.Intent
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import android.widget.Toast
import android.Manifest
import android.provider.Settings
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import android.app.Activity
import android.content.ActivityNotFoundException

class EditProfileActivity() : AppCompatActivity() {

private lateinit var imageView: ImageView
private var imageUri: Uri? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_profile)
val button4 = findViewById<Button>(R.id.button4)
button4.setOnClickListener {
val eIntent = Intent(applicationContext, SecondActivity::class.java)
eIntent.putExtra("first_name", findViewById<TextView>(R.id.textview_name).text)// - имя
eIntent.putExtra("last_name" , findViewById<TextView>(R.id.textview_surname).text)// - фамилия
eIntent.putExtra("age", findViewById<TextView>(R.id.textview_age).text)// - возраст
launcher.launch(eIntent)
}
imageView = findViewById(R.id.imageview_photo)
imageView.setOnClickListener {
val items = arrayOf("Сделать фото", "Выбрать фото")

MaterialAlertDialogBuilder(it.context)
.setTitle("Выберите действие")
.setItems(items) { dialog, which ->
when(which) {
0 -> if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
MaterialAlertDialogBuilder(this)
.setTitle("Инфо")
.setIcon(android.R.drawable.ic_menu_camera)
.setMessage("Чтобы сделать фото нужно предоставить доступ к камере")
.setPositiveButton("Дать доступ") { dialog, _ ->
permissionCamera.launch(Manifest.permission.CAMERA)
}
.setNegativeButton("Отмена") { dialog, _ ->
dialog.cancel()
}
.show()
} else {
permissionCamera.launch(Manifest.permission.CAMERA)
}
1 -> resultImageContent.launch("image/*")
else -> return@setItems
}
}
.show()
}
findViewById<Toolbar>(R.id.toolbar).apply {
inflateMenu(R.menu.menu)
setOnMenuItemClickListener {
when (it.itemId) {
R.id.send_item -> {
openSenderApp()
true
}
else -> false
}
}
}
}
private val resultImageContent = registerForActivityResult(ActivityResultContracts.GetContent())
{
imageUri = it
it?.let { populateImage(it) }
}
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result -> result ?: return@registerForActivityResult

if(result.resultCode == Activity.RESULT_OK) {
result.data?.extras?.let { extras ->
var text = extras.getString("first_name").toString()
findViewById<TextView>(R.id.textview_name).text = text
text = extras.getString("last_name").toString()
findViewById<TextView>(R.id.textview_surname).text = text
text = extras.getString("age").toString()
findViewById<TextView>(R.id.textview_age).text = text
}
}
}
val camera = registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap ->
findViewById<ImageView>(R.id.imageview_photo).setImageBitmap(bitmap)
}

private val permissionCamera = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
when {
granted -> {
//Пермишен к камере получен, запускаем камеру
val bitmap = BitmapFactory.decodeResource(resources, R.drawable.cat)
imageUri = Uri.parse("android.resource://$packageName/${R.drawable.cat}")
imageView.setImageBitmap(bitmap)
camera.launch(null)
}
!shouldShowRequestPermissionRationale(Manifest.permission.CAMERA) -> {

MaterialAlertDialogBuilder(this)
.setTitle("Инфо")
.setMessage("Доступ к камере запрещен")
.setNeutralButton("Открыть настройки") { dialog, which ->
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
val uri = Uri.fromParts("package", packageName, null)
data = uri
}
startActivity(intent)
}
.show()

}
else -> {
Toast.makeText(this, "Отмена", Toast.LENGTH_SHORT).show()
}
}
}

/**
* Используйте этот метод чтобы отобразить картинку полученную из медиатеки в ImageView
*/

private fun populateImage(uri: Uri) {
val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(uri))
imageView.setImageBitmap(bitmap)
}

private fun openSenderApp() {
val first_name = findViewById<TextView>(R.id.textview_name).text
val last_name = findViewById<TextView>(R.id.textview_surname).text
val age = findViewById<TextView>(R.id.textview_age).text
try {
val intent = Intent(Intent.ACTION_SEND)
intent.setPackage("org.telegram.messenger")
intent.putExtra(Intent.EXTRA_TEXT, "${first_name}\n${last_name}\n${age}")
intent.setType("image/*")
if (imageUri != null) {
intent.putExtra(Intent.EXTRA_STREAM, imageUri)
}
startActivity(Intent.createChooser(intent, "Отправить:"));
}
catch (exception: ActivityNotFoundException) {
Toast.makeText(this, "Telegram не установлен", Toast.LENGTH_SHORT).show()
}
}
}
42 changes: 42 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,42 @@
package otus.gpb.homework.activities

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText

class SecondActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val editText = findViewById<EditText>(R.id.editText)
val editText1 = findViewById<EditText>(R.id.editText1)
val editText2 = findViewById<EditText>(R.id.editText2)
val saveButton = findViewById<Button>(R.id.saveButton)
val first_name = getIntent().getStringExtra("first_name")
editText.setText(first_name)
val last_name = getIntent().getStringExtra("last_name")
editText1.setText(last_name)
val age = getIntent().getStringExtra("age")
editText2.setText(age)
saveButton.setOnClickListener {
val intent = Intent()
intent.putExtra("first_name", editText.text.toString())// - имя
intent.putExtra("last_name" , editText1.text.toString())// - фамилия
intent.putExtra("age", editText2.text.toString())// - возраст
setResult(RESULT_OK, intent)
finish()
}
}

override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
}

override fun onBackPressed() {
super.onBackPressed()
setResult(RESULT_CANCELED)
}
}
Binary file added app/src/main/res/drawable/cat.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions app/src/main/res/drawable/ic_baseline_add_photo_alternate_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="80dp"
android:height="80dp"
android:tint="#33000000"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@android:color/white"
android:pathData="M19,7v2.99s-1.99,0.01 -2,0L17,7h-3s0.01,-1.99 0,-2h3L17,2h2v3h3v2h-3zM16,11L16,8h-3L13,5L5,5c-1.1,0 -2,0.9 -2,2v12c0,1.1 0.9,2 2,2h12c1.1,0 2,-0.9 2,-2v-8h-3zM5,19l3,-4 2,3 3,-4 4,5L5,19z" />
</vector>
5 changes: 5 additions & 0 deletions app/src/main/res/drawable/ic_baseline_send_24.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<vector android:autoMirrored="true" android:height="24dp"
android:tint="#FFFFFF" android:viewportHeight="24"
android:viewportWidth="24" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
<path android:fillColor="@android:color/white" android:pathData="M2.01,21L23,12 2.01,3 2,10l15,2 -15,2z"/>
</vector>
73 changes: 73 additions & 0 deletions app/src/main/res/layout/activity_edit_profile.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".EditProfileActivity">

<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:title="Профиль"
app:titleTextColor="@color/white" />

<ImageView
android:id="@+id/imageview_photo"
android:layout_width="120dp"
android:layout_height="160dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/toolbar"
app:srcCompat="@drawable/ic_baseline_add_photo_alternate_24" />

<TextView
android:id="@+id/textview_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:hint="Имя"
android:textSize="18dp"
app:layout_constraintStart_toEndOf="@+id/imageview_photo"
app:layout_constraintTop_toTopOf="@+id/imageview_photo" />

<TextView
android:id="@+id/textview_surname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:hint="Фамилия"
android:textSize="18dp"
app:layout_constraintStart_toStartOf="@+id/textview_name"
app:layout_constraintTop_toBottomOf="@+id/textview_name" />

<TextView
android:id="@+id/textview_age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:hint="Возраст"
android:textSize="18dp"
app:layout_constraintStart_toStartOf="@+id/textview_surname"
app:layout_constraintTop_toBottomOf="@+id/textview_surname" />

<Button
android:id="@+id/button4"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Редактировать профиль"
app:layout_constraintStart_toStartOf="@+id/textview_age"
app:layout_constraintTop_toBottomOf="@+id/textview_age" />

</androidx.constraintlayout.widget.ConstraintLayout>
Loading