Skip to content

Useful Util Composables and functions

kevin yang edited this page Oct 16, 2024 · 1 revision

Useful Utility Functions and Composables

Package: com.android.shelfLife.ui.utils

This section contains various utility functions and composable components to assist in your Android development workflow. The utilities range from UI components to date/time conversions and string manipulations.


1. DropdownFields - Composable Dropdown Menu

Creates a working dropdown menu with customizable options and labels. Ideal for user selection from a predefined set of options.

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun <T> DropdownFields(
    label: String,
    options: Array<T>,
    selectedOption: T,
    onOptionSelected: (T) -> Unit,
    expanded: Boolean,
    onExpandedChange: (Boolean) -> Unit,
    optionLabel: (T) -> String,
    modifier: Modifier = Modifier
) {
    ExposedDropdownMenuBox(
        expanded = expanded,
        onExpandedChange = { onExpandedChange(!expanded) },
        modifier = modifier
    ) {
        OutlinedTextField(
            value = optionLabel(selectedOption),
            onValueChange = {},
            label = { Text(label) },
            readOnly = true,
            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
            modifier = Modifier.fillMaxWidth().menuAnchor()
        )
        ExposedDropdownMenu(
            expanded = expanded,
            onDismissRequest = { onExpandedChange(false) }
        ) {
            options.forEach { option ->
                DropdownMenuItem(
                    text = { Text(optionLabel(option)) },
                    onClick = {
                        onOptionSelected(option)
                        onExpandedChange(false)
                    }
                )
            }
        }
    }
}

Parameters:

  • T: Generic type for dropdown options.
  • label: String - Label for the field.
  • options: Array - The list of options to display.
  • selectedOption: T - Currently selected option.
  • onOptionSelected: Lambda - Callback when an option is selected.
  • expanded: Boolean - Whether the dropdown is expanded.
  • onExpandedChange: Lambda - Triggered when the dropdown state changes.
  • optionLabel: Lambda - Formats how the options are displayed.

2. ErrorPopUp - Composable Error Dialog

Displays an error pop-up dialog, useful for handling and showing error messages.

@Composable
fun ErrorPopUp(showDialog: Boolean, onDismiss: () -> Unit, errorMessages: List<String>) {
    if (showDialog) {
        Dialog(onDismissRequest = onDismiss) {
            Surface(
                shape = RoundedCornerShape(12.dp),
                modifier = Modifier.padding(16.dp).widthIn(min = 280.dp, max = 400.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "Error", 
                        modifier = Modifier.padding(bottom = 16.dp), 
                        fontSize = 24.sp
                    )

                    Column(modifier = Modifier.padding(bottom = 16.dp)) {
                        errorMessages.forEach { message ->
                            Text(text = message, modifier = Modifier.padding(bottom = 8.dp))
                        }
                    }

                    Button(onClick = onDismiss) { Text("OK") }
                }
            }
        }
    }
}

Parameters:

  • showDialog: Boolean - Whether the dialog should be shown.
  • onDismiss: Lambda - Callback when the dialog is dismissed.
  • errorMessages: List - A list of error messages to display.

3. getTotalMinutes - Convert Timestamp to Minutes

Converts a Firebase Timestamp into an integer representing the total minutes.

fun getTotalMinutes(timestamp: Timestamp): Int {
    return (timestamp.seconds / 60).toInt() // Convert seconds to minutes
}

Parameters:

  • timestamp: Firebase Timestamp object.

Returns:

  • Integer representing the total minutes.

4. formatTimestampToDate - Convert Timestamp to String (Date Format)

Converts a Timestamp into a formatted date string (dd/MM/yyyy).

fun formatTimestampToDate(timestamp: Timestamp): String {
    val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
    return sdf.format(timestamp.toDate())
}

Parameters:

  • timestamp: Firebase Timestamp object to format.

Returns:

  • Formatted date string (dd/MM/yyyy).

5. formatDateToTimestamp - Convert String to Timestamp

Converts a date string (dd/MM/yyyy) into a Firebase Timestamp.

fun formatDateToTimestamp(dateString: String): Timestamp {
    val sdf = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
    val date = sdf.parse(dateString)
    return Timestamp(date)
}

Parameters:

  • dateString: String in dd/MM/yyyy format.

Returns:

  • Corresponding Firebase Timestamp.

6. fromCapitalStringtoLowercaseString - Format String

Converts a string into lowercase with the first letter capitalized.

fun fromCapitalStringtoLowercaseString(enum: String): String {
    return enum.lowercase().replaceFirstChar { it.uppercase() }
}

Parameters:

  • enum: The string to convert.

Returns:

  • A string where the first letter is capitalized and the rest is in lowercase.