Introduction
In this article, we will continue
with the practical demonstration of Android development using our “Demo One”
Android project as an example.
Note that in my previous article, I
demonstrated how to add AlertDialog to MainActivity.kt, and programmed it to
show when the “Click Here to Proceed” button is clicked. The AlertDialog
contains a button with the text “NEXT” (as in Figure 1).
Figure 1
When the “NEXT” button is tapped or
clicked, the AlertDialog will close, and then, the app will navigate back to
MainActivity.
In this article, we will add a new
Activity named “SecondActivity”. Next, with the use of “intent”, we will
program the AlertDialog “NEXT” button to navigate to SecondActivity when
tapped. Next, we will add top app bar to our SecondActivity.
Let us now open our “Demo One”
project (as in Figure 2) and continue with the development process.
Figure 2
Creation of a new Activity named
“SecondActivity”
There are different methods of
creating a new Activity in Android Studio. In this demonstration, we will be
using the following simple method.
To create a new Activity, click on
“File” from the menu bar. Next, click on “New”. Next, click on “Activity”, and
then, click on “Gallery” (as in Figure 3).
Figure 3
Next, select the template for empty
Compose Activity, and then click on “Next” (as in Figure 4).
Figure 4
Next, modify the name of the Activity
to “SecondActivity”, and then, click on “Finish” (as in Figure 5).
Figure 5
SecondActivity.kt is now created. You
can click on “Build & Refresh” from the Split screen to preview the design
(as in Figure 6).
Figure 6
Addition of Intent
We will now add an explicit intent to
the “NEXT” button that is on our AlertDialog. Note that an explicit intent is
used to start an Activity within the same Android application. In other words,
it is a mechanism that can be used to navigate the user from one screen to
another within the same application.
To add the intent, we will open the
MainActivity.kt, and go to the section for the DemoScreen composable function. Inside
the AlertDialog, we will locate the confirmButton, and then, above Button
composable, we will call the current local context and save it in an immutable
variable named “context” (as in figure 7). If LocalContext is underlined in
red, you can press “alt + enter” key to import it. Note that LocalContext
provides access to the current Context.
val context = LocalContext.current
Figure 7
Next, inside the onClick function of
the button, we will add our intent to the existing codes (as in Figure 8).
val intent =
Intent(context, SecondActivity::class.java)
context.startActivity(intent)
Figure 8
With that done, SecondActivity screen
will open when the “NEXT” button on the AlertDialog is tapped.
Addition of Top App Bar
The “top app bar” is also known as
“action bar” or “toolbar”. It can be used for branding, and for the display of
screen title, navigation and actions.
In the Top App Bar, we will have a
back navigation icon, a Text composable for displaying our screen title, a home
icon button, another icon button for “More”, and “About” DropDownMenu.
First, we will open SecondActivity.kt
and delete the default lines of code related to “Greeting”.
The content of SecondActivity.kt
should now be updated as shown in Figure 9.
Figure 9
Inside SecondActivity.kt, we will add
a composable function named “SecondScreen”.
Inside the SecondScreen function, we
will add a Scaffold as its first element. With the Scaffold, we can add
Material components like TopAppBar, NavigationBar, FloatingActionButton, among
others.
Scaffold receives an instance of
paddingvalues that should be applied to the content root. For now, we will
suppress the scaffold padding parameter by adding a SuppressLint annotation
above the SecondScreen function. Also, above the function, we will add the
OptIn annotation for ExperimentalMaterial3 Api (as shown in Figure 10).
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
Figure 10
Let us now update the scaffold by
adding some lines of code for our Top Bar.
First, we will call the TopAppBar
function and define the color, title and NavigationIcon (as shown in Figure 11).
Figure 11
Next, we will use the “actions”
function, and inside it, we will add “Home” icon for our action button, a
MoreVert icon that will make the dropdown menu items to be shown when tapped,
and “About” for our dropdown menu item (as in Figure 12). Note that above the
IconButton function, we have remembered a mutable state, set its initial value
to “false” and stored it in a variable named “showMenu”. Inside the onClick
listener of the MoreVert IconButton, we have set the value of showMenu to
“true”. Therefore, when it is clicked, the dropdown menu items will show. Next,
for the DropdownMenu function, we have set the value of the “expanded”
parameter to showMenu.value which is “false”; also, for the onDismissRequest,
we have set the value of showMenu to “false”. Furthermore, in the body of the
DropdownMenu function, we have added our “About” DropdownMenuItem, and set the
value of showMenu to “false” in its onClick parameter, so as to simply close
the dropdown menu when “About” is tapped. Note that we can still add more
actions to be performed inside the onClick parameter of the “About” dropdown
item.
Figure 12
Next, we will add a Column composable
that will fill maximum width of the screen and have a padding of 8.dp. Inside
the Column layout, we will add a Spacer with a height of 60.dp and some text (as
in Figure 13).
Figure 13
Testing the App
We can now scroll up to the
SetContent function and call SecondScreen().
Also, inside our Preview, let us
update the function name to “SecondScreenPreview” and then, we will call
SecondScreen(), as in Figure 14.
Figure 14
Next, we will run our emulator and
test how the app works. The app worked as expected (as shown in Figure 15).
Figure 15
That’s it.
Thank you for reading.
Happy learning and coding.
package com.ajirelab.demoone
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.ajirelab.demoone.ui.theme.DemoOneTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DemoOneTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DemoScreen()
}
}
}
}
}
@Composable
fun DemoScreen(){
Box(modifier = Modifier.fillMaxSize()) {
Image(
painter = painterResource(id = R.drawable.demo_bg),
contentDescription = "Demo Background",
contentScale = ContentScale.FillBounds,
modifier = Modifier.matchParentSize()
)
}
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = "Welcome", fontSize = 30.sp, fontWeight = FontWeight.Bold)
//Alert Dialog to be show when button is clicked
val showAlertMessage = remember{ mutableStateOf(false) }
if(showAlertMessage.value){
AlertDialog(
onDismissRequest = {showAlertMessage.value = false},
title = {Text(text = "CONFIRM")},
text = {Text(
text= "Hello User! To navigate to the next page, tap on NEXT button. Thank you.",
modifier = Modifier.verticalScroll(rememberScrollState())
)},
confirmButton = {
val context = LocalContext.current
Button(
onClick = {
showAlertMessage.value= false
val intent = Intent(context, SecondActivity::class.java)
context.startActivity(intent)
},
colors = ButtonDefaults.buttonColors(Color.Black)
) {
Text(text = "NEXT", color = Color.White, fontWeight = FontWeight.Bold)
}
}
)
}
Button(
onClick = { showAlertMessage.value= true},
modifier = Modifier.padding(6.dp),
colors = ButtonDefaults.buttonColors(Color.Magenta)
) {
Text(text = "Click Here to Proceed", fontSize = 18.sp)
}
}
}
@Preview(name = "Light Mode", showBackground = true, showSystemUi = true)
@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, showSystemUi = true)
@Composable
fun DemoScreenPreview(){
DemoScreen()
}
package com.ajirelab.demoone
import android.annotation.SuppressLint
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.ajirelab.demoone.ui.theme.DemoOneTheme
class SecondActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DemoOneTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
SecondScreen()
}
}
}
}
}
@Preview(name = "Light Mode", showBackground = true, showSystemUi = true)
@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES, showSystemUi = true)
@Composable
fun SecondScreenPreview() {
DemoOneTheme {
SecondScreen()
}
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SecondScreen() {
Scaffold(
topBar = {
TopAppBar(
colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = Color.Magenta),
title = {
Text(text = "Demo One App", color = Color.White, fontWeight = FontWeight.Bold)
},
navigationIcon = {
IconButton(onClick = { }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Back", tint = Color.White)
}
},
actions = {
IconButton(onClick = { }) {
Icon(Icons.Filled.Home, contentDescription = "Home", tint = Color.White)
}
//Codes related to DropDownMenu starts here
val showMenu = remember { mutableStateOf(false) } //added for dropdown app bar menu
IconButton(onClick = {showMenu.value = true}) {
Icon(Icons.Default.MoreVert, contentDescription = null, tint = Color.White)
}
DropdownMenu(expanded = showMenu.value, onDismissRequest = {showMenu.value= false}) {
DropdownMenuItem(text = { Text(text = "About")}, onClick = {showMenu.value = false })
}
//Codes related to DropDownMenu ends here
}
) //TopAppBar ends here
} //topBar ends here
) {
Column(
modifier = Modifier.fillMaxWidth().padding(8.dp)
) {
//The Spacer below is necessary so as to ensure that nothing is
//hidden behind the TopAppBar.
Spacer(modifier = Modifier.height(60.dp))
Text(text = "Welcome to the second screen.")
}
}
}
Comments
Post a Comment