Android Kotlin - Menus e Activities
De Aulas
(Redirecionado de Android Kotlin - Menus)
Afluentes: Dispositivos Móveis
Visual
Nesse exemplo vamos criar um projeto com um Basic Activity, mas vamos limpar ele um pouco e tirar os fragmentos. Vamos trabalhar com multiplas Activities.
Nosso exemplo pronto deve parecer com as imagens abaixo.
strings.xml
1<resources>
2 <string name="app_name">Menu and Activity Test</string>
3 <string name="action_settings">Settings</string>
4 <string name="action_other">Other</string>
5 <string name="name">Name</string>
6 <string name="age">Age</string>
7 <string name="button_execute">Execute</string>
8 <string name="message">Your name is %1$s and your age are %2$s years old.</string>
9</resources>
Menus
No menu_main.xml, adiciona-se os novos itens. A informação orderInCategory é a ordem que os itens do meno irão aparecer.
<item android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never"/>
<item android:id="@+id/action_other"
android:title="@string/action_other"
android:orderInCategory="101"
app:showAsAction="never"/>
MainActivity.kt
Nos programa kotlin, basta adicionar as ações dentro da opção no when
.
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val myText: TextView = findViewById(R.id.textViewHello)
return when (item.itemId) {
R.id.action_settings -> {
myText.text = "Settings option"
return true
}
R.id.action_other -> {
myText.text = "Other option"
return true
}
else -> super.onOptionsItemSelected(item)
}
}
Layouts
content_main.xml
<?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"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<EditText
android:id="@+id/editTextName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="116dp"
android:ems="10"
android:hint="@string/name"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editTextAge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/age"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextName" />
<TextView
android:id="@+id/textViewMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:textColor="#734BB9"
android:textScaleX="1.0"
android:textSize="20sp"
android:textStyle="normal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editTextAge" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_other.xml
<?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=".OtherActivity">
<TextView
android:id="@+id/textViewName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="36dp"
android:text="@string/name"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textViewAge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="@string/age"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewName" />
<Button
android:id="@+id/buttonExecute"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="88dp"
android:text="@string/button_execute"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textViewAge" />
</androidx.constraintlayout.widget.ConstraintLayout>
Kotlin
MainActivity.kt
package com.example.menuteste
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.ui.AppBarConfiguration
import android.view.Menu
import android.view.MenuItem
import android.widget.EditText
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import com.example.menuteste.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
binding.fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
private fun openOtherActivity() {
val editTextName : EditText = findViewById(R.id.editTextName)
val editTextAge : EditText = findViewById(R.id.editTextAge)
val intent = Intent(this, OtherActivity::class.java)
intent.putExtra("name", editTextName.text.toString())
intent.putExtra("age", editTextAge.text.toString())
getResult.launch(intent)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> true
R.id.action_other -> {
openOtherActivity()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private val getResult =
registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
if (it.resultCode == Activity.RESULT_OK) {
if (it.data != null) {
val textViewMessage : TextView = findViewById(R.id.textViewMessage)
textViewMessage.text = it.data?.getStringExtra("message")
}
}
}
}
OtherActivity.kt
package com.example.menuteste
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
class OtherActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_other)
val textViewName: TextView = findViewById(R.id.textViewName)
val textViewAge : TextView = findViewById(R.id.textViewAge)
val bundle = intent.extras
if (bundle != null) {
textViewName.text = bundle.getString("name")
textViewAge.text = bundle.getString("age")
}
val buttonExecute: Button = findViewById(R.id.buttonExecute)
buttonExecute.setOnClickListener {
val message = getString(R.string.message, textViewName.text, textViewAge.text)
val data = Intent()
data.putExtra("message", message)
setResult(RESULT_OK, data)
finish()
}
}
}