Skip to main content

Android Development: Adding New Activity, Explicit Intent and Top App Bar with Jetpack Compose

 

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.


Compilation of the Main Lines of Code
MainActivity.kt
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()
}

SecondActivity.kt
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

Popular Posts

Android Development: Addition of Bottom Navigation Bar with Kotlin and Jetpack Compose

  Introduction In this article, we will add bottom navigation bar to the second screen of the “Demo One” App that I have been using for demonstrations in my previous Android development articles. The bottom navigation bar will have three navigation items, which are, “Home”, “Info” and “Settings”.  The navigation items would be programmed to render their contents on the screen accordingly when clicked or tapped. Note that the “Demo One” Android project already had a TopAppBar, as added in my previous article. The user interface of the second screen of the Demo One App is as shown in Figure 1. Figure 1 Addition of Needed Dependency The dependency that we will need for the addition of bottom navigation bar to our Android project is called “navigation”. Let us now open the module-level build.gradle file in our Android project and add the version 2.6.0 of the navigation dependency. After the addition of the dependency, we will connect to the internet and then click on “Sync Now” as

Android Development: Using Alert Dialog with Button in Jetpack Compose

  Introduction: In Android application development, buttons could be programmed to perform some actions (such as navigating to another screen, showing toast message, closing the app, among others) when the user taps or clicks on them. In this article, we will learn how to make a button to perform the action of displaying an alert message to the user. This would be achieved using a composable function called AlertDialog. Note that we will be demonstrating this with the 'Click Here to Proceed' button located inside the ‘DemoScreen’ composable function in our 'Demo One' Android project from my previous article. Demonstration: First, we will open the 'Demo One' project. ‘Demo One’ project is now opened as shown in Figure 1. Figure 1 Next, above the button composable in our ‘DemoScreen’ composable function, we will define a mutable state variable, set its value to ‘false’, and store it with the name 'showAlertMessage' (as shown in Figure 2). Note th

Literature Review: An Important Exercise for Students and Researchers

  Introduction Review of literature is a very important exercise which researchers as well as students at both undergraduate and postgraduate levels cannot shy away from, as it identifies and summarizes research and theories that are relevant to their area of interest, and as well sets good foundation for research or theses writing. In this article, we will consider some aspects of literature review such as its meaning, its significance, what it entails, steps to take in writing a good literature review, and some of the things that we need to avoid while reviewing literature. Meaning of literature review Let us first break down the key concepts and see what the dictionary has for us as per the meaning of ‘Literature’ and ‘Review’. In Oxford Advanced Learner’s Dictionary (8 th Edition), literature means “pieces of writing or printed information on a particular subject”. Also, Longman Dictionary of Contemporary English defines literature as "all the books, articles, etc.