Add button to take a photo
[android-PittiHelloWorld.git] / app / src / main / java / com / example / pittihelloworld / MainActivity.kt
1 package com.example.pittihelloworld
2
3 import android.app.Activity
4 import android.content.Intent
5 import android.graphics.Bitmap
6 import androidx.appcompat.app.AppCompatActivity
7 import android.os.Bundle
8 import android.provider.MediaStore
9 import android.view.View
10 import android.widget.EditText
11 import android.widget.TextView
12 import kotlinx.android.synthetic.main.activity_main.*
13
14 const val EXTRA_MESSAGE = "com.example.pittihelloworld.MESSAGE"
15 const val REQUEST_IMAGE_CAPTURE = 1
16
17 class MainActivity : AppCompatActivity() {
18     override fun onCreate(savedInstanceState: Bundle?) {
19         super.onCreate(savedInstanceState)
20         setContentView(R.layout.activity_main)
21     }
22
23     fun sendMessage(view: View) {
24         val message = messageText.text.toString()
25         val intent = Intent(this, DisplayMessageActivity::class.java).apply {
26             putExtra(EXTRA_MESSAGE, message)
27         }
28         startActivity(intent)
29     }
30
31     fun takePhoto(view: View) {
32         Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
33             takePictureIntent.resolveActivity(packageManager)?.also {
34                 startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
35             }
36         }
37     }
38
39     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
40         super.onActivityResult(requestCode, resultCode, data)
41         textViewPhotoResult.text = "result code: " + resultCode.toString()
42         if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK && data != null) {
43             val extras = data.extras
44             if (extras != null) {
45                 val imageBitmap = extras.get("data") as Bitmap
46                 imageViewPhoto.setImageBitmap(imageBitmap)
47             }
48         }
49     }
50 }