Your Second Kotlin Android App

Aug 29 2023 · Kotlin 1.8.21, Android 13, Android Studio Flamingo | 2022.2.1

Part 2: Create Your Views

12. Create Shared UI Components

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 11. Build a List Item View Next episode: 13. Use LazyLayouts

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 12. Create Shared UI Components

You have created a list item view that can display a list of items in your app. In this episode, you’ll create more UI components that you can share among different screens in your app.

You’ll start by creating the ListMakerTopAppBar component that you’ll use later to display the top bar for your app.

Inside the views, package create a new Kotlin file named ListMakerTopAppBar.kt.

Add the following code to the file:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ListMakerTopAppBar(title: String, showBackButton: Boolean, onBackPressed: () -> Unit) {
    TopAppBar(
        title = {
            Text(text = title)
        },
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer
        ), navigationIcon = {
            if (showBackButton) {
                IconButton(onClick = onBackPressed) {
                    Icon(
                        imageVector = Icons.Default.ArrowBack,
                        contentDescription = stringResource(id = R.string.cd_back_icon)
                    )
                }
            }
        }
    )
}

Here’s a breakdown of the code:

  • You’ve created a new composable function named ListMakerTopAppBar that will create a top app bar for your app. The function has three parameters:
    • title - A string specifying the name of the app.
    • showBackButton - A boolean that determines if the back button should be displayed.
    • onBackPressed - This is a function that will be called when the back button is clicked.
  • You’ve used the TopAppBar Composable to create the top app bar. It has the following parameters:
    • title - This is a composable that will be used to display the title of your app. You’ve passed a Text composable that displays the title parameter.
    • colors - This is a TopAppBarColors object that set the colors of the top app bar. You’ve used the TopAppBarDefaults.topAppBarColors function to create a TopAppBarColors object that uses the primary color of your app as the background color of the top app bar.
    • navigationIcon - This is a composable that will be used to display the navigation icon. You’ve used an IconButton composable to display the back button. The IconButton composable has the following parameters:
      • onClick - This is a function that will be called when the back button is clicked. You’ve passed the onBackPressed parameter.
      • content - This is a composable that will be used to display the icon. You’ve used an Icon composable to display the back arrow icon. The Icon composable has the following parameters:
        • imageVector - This is an ImageVector object that will be used to display the icon. You’ve passed the Icons.Default.ArrowBack object.
        • contentDescription - This is a string that will be used to describe the icon. You’ve passed a string resource.

The stringResource(id = R.string.cd_back_icon) shows an error since you haven’t created the string resource yet. To create the resource, press Alt + Enter on Windows or Option + Return on Mac to show the quick fix menu. Select Create resource string ‘cd_back_icon’. Specify Back icon as the resource value and press Ok. This creates a new string resource named cd_back_icon in the strings.xml file.

Notice that you’ve used the @OptIn(ExperimentalMaterial3Api::class) annotation to opt into the experimental Material 3 API. This is because the TopAppBar composable is part of the experimental Material 3 API.

Next, you’ll create the ListMakerFloatingActionButton composable to display the floating action button for your app. Still inside the views package, create a file named ListMakerFloatingActionButton.

Inside the file, add the following code:

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ListMakerFloatingActionButton(
  title: String,
  inputHint: String,
  onFabClick: (String) -> Unit
) {
  var showDialog by remember { mutableStateOf(false) }
  var taskName by remember { mutableStateOf("") }

  FloatingActionButton(
    onClick = {
      showDialog = true
    },
    content = {
      Icon(
        imageVector = Icons.Default.Add,
        contentDescription = stringResource(id = R.string.cd_add_icon)
      )
    }
  )

  if (showDialog) {
    AlertDialog(
      onDismissRequest = { showDialog = false },
      title = { Text(text = title) },
      text = {
        OutlinedTextField(
          value = taskName,
          onValueChange = { taskName = it },
          label = { Text(text = inputHint) },
          singleLine = true
        )
      },
      confirmButton = {
        Button(
          onClick = {
            showDialog = false
            onFabClick(taskName)
            taskName = ""
          },
          content = {
            Text(text = stringResource(id = R.string.label_create))
          }
        )
      },
    )
  }
}

Resolve the string resources error by creating it as before, passing the Add a new task icon for the cd_add_icon. In the code above, you’ve created a new composable function named ListMakerFloatingActionButton The function has three parameters:

  • title - This is a string that specifies the title of the dialog to be displayed when the floating action button is clicked.
  • inputHint - This is a string that specifies the hint for the text field in the dialog.
  • onFabClick - This is a function that will be called when the floating action button is clicked. The function has a string parameter that will pass the text entered in the text field in the dialog.

Inside the function, there are two variables”:

  • showDialog
  • taskName

The showDialog variable is a boolean that determines if the dialog should be displayed. The taskName variable is a string that will store the text entered in the text field in the dialog. You’ve used the remember function to create these variables. The remember function is used to create a state whose value will be remembered when the composable is recomposed.

Below these, you’ve created a FloatingActionButton composable that has two parameters:

  • onClick - This is a function that will be called when the floating action button is clicked. Inside the lambda expression, you set the showDialog variable to true when the floating action button is clicked.
  • content - This is used to display the icon. You’ve used an Icon composable to display the add icon. The Icon composable is similar to the one you had created in ListMakerTopAppBar.

Below the FloatingActionButton composable, you’ve used an if statement to check if the showDialog variable is true.

Resolve the string resource error by passing the Create string for the label_create string resource.

You’ve used the AlertDialog composable to display the dialog. The AlertDialog composable has the following parameters:

  • onDismissRequest - This function will be called when the dialog is dismissed. Inside the lambda expression, you set the showDialog variable to false when the dialog is dismissed.
  • title - This is used to display the title of the dialog. You’ve used a Text composable to display the title parameter.
  • text - This is used to display the content of the dialog. You’ve used an OutlinedTextField composable to display the text field. The OutlinedTextField composable has the following parameters:
    • value - This is a string that will be used to display the text in the text field. You’ve used the taskName variable.
    • onValueChange - This is a function that will be called when the text in the text field changes. You’ve used a lambda expression to set the taskName variable to the new value.
    • label - This is used to display the hint for the text field. You’ve used a Text composable to display the inputHint parameter.
    • singleLine - This limits the input to a single line.
  • confirmButton - This is used to display the confirm button. You’ve used a Button composable to display the confirm button.