Software Development

Android App Development with JetPack Compose.

admin
16 October 2023
Android App Development with JetPack Compose.

First, let's learn about what Jetpack Compose is

Jetpack Compose is a modern Android UI toolkit developed by Google for building native user interfaces in a more declarative and efficient way.It allows developers to create UI components and layouts using a Kotlin-based domain-specific language, making it easier to build dynamic and interactive user interfaces for Android applications. Buttons, Card, Images, AlertDialog, and Single Choice Dialog are all components or UI elements that can be created and customized using Jetpack Compose.

How to use the Preview and Preview Parameter

@Preview is used to annotate a composable function, indicating that it should be displayed in the Compose Preview. The Compose Preview is a design-time feature that allows you to see and interact with your UI components as you develop them.

Example:

				
					@Composable
@Preview
fun MyComposablePreview() {
    // Call your composable function here to preview it
    MyComposable()
}


				
			

@PreviewParameter is used to define parameters for your preview functions. This is particularly useful when you want to create multiple previews for the same composable function with different parameter values to visualize various states or scenarios.

Example:

				
					@Composable
@Preview
fun MyComposablePreview(
    @PreviewParameter(MyParameterProvider::class) myParameter: MyParameter
) {
    MyComposable(myParameter)
}


				
			

How to display a TextField (EditText) and apply various styles on it?

Jetpack Compose is a modern way to build UIs in Android, and it’s different from traditional XML layouts. Here’s how you can create and style a TextField in Jetpack Compose:

  1. Create a TextField:
				
					
@Composable
fun MyTextField() {
    var textState by remember { mutableStateOf(TextFieldValue()) }

    BasicTextField(
        value = textState,
        onValueChange = { textState = it },
        modifier = Modifier
            .padding(16.dp)
            .background(Color.LightGray) // Set the background color
            .padding(8.dp) // Add padding
            .border(1.dp, Color.Black) // Add a border
            .fillMaxWidth() // Make it occupy the entire width
    )
}


				
			

2. Apply Styles Programmatically:

You can apply various styles programmatically by using the Modifier system in Jetpack Compose. In the example above, we applied a background color, padding, and a border. You can customize the background color, border, padding, text color, and other visual properties as needed.

3. Customize Additional Properties:

 You can further customize the TextField by adjusting properties such as text size, font, and more within the BasicTextField or by adding additional modifiers.

Creating a notepad app with Android Jetpack Compose is a great project to showcase the power and flexibility of this modern UI toolkit.

Prerequisites:

Before you begin, make sure you have the following:

  • Android Studio (with Jetpack Compose plugin) installed.
  • Basic knowledge of Kotlin programming.
Prerequisites:

Step 1: Create a New Android Project

  1. Open Android Studio.
  2. Select “Start a new Android Studio project.”
  3. Choose an appropriate project template (e.g., Empty Compose Activity).
  4. Set your app’s name and package name.
  5. Click “Finish.”

Step 2: Set Up Dependencies

In your app’s build.gradle file, make sure you have the following dependencies for Jetpack Compose:

				
					android {
   buildFeatures {
       compose true
   }
   composeOptions {
       kotlinCompilerExtensionVersion 'X.X.X' // Use latest version
   }
}
dependencies {
   implementation "androidx.compose.ui:ui:X.X.X" // Use latest version
   implementation "androidx.compose.material:material:X.X.X" // Use latest
   implementation "androidx.activity:activity-compose:X.X.X" // Use latest
   implementation "androidx.navigation:navigation-compose:X.X.X" // Use latest
}

				
			

Sync your project to apply the changes.

Step 3: Creating a Simple Notepad App with Android Jetpack Compose

In this tutorial, we will guide you through the process of building a straightforward notepad app using Android Jetpack Compose, a modern UI toolkit that simplifies the creation of Android apps through declarative UI programming. The app will follow a step-by-step structure:

 

1. Create NavigationScreen.kt
				
					sealed class NavigationScreen(val route:String)
{
   object SplashScreen : NavigationScreen("splashScreen")
   object HomeScreen : NavigationScreen("homeScreen")
   object CreateNotesScreen : NavigationScreen("createNoteScreen")
}

				
			
2. Create StartNavigation.kt

In this file declare all the routes of your app like this:

				
					fun StartNavigation(context: Context) {


   val navController = rememberNavController()
   NavHost(navController = navController, startDestination = NavigationScreen.SplashScreen.route) {
       composable(NavigationScreen.SplashScreen.route)
       {
           SplashScreenUI(navController)
       }
      composable(NavigationScreen.HomeScreen.route)
       {
           HomeScreenUI(context,navController)
       }
      composable(NavigationScreen.CreateNotesScreen.route)
       {
           CreateNotesUI(context,navController)
       }
   }
}

				
			
3. Splash Screen

We will begin by implementing a splash screen that will be displayed for two seconds when the app is launched. This screen serves as a welcoming introduction to the user.

				
					@Composable
fun SplashScreen(navController: NavController) {
   LaunchedEffect(true) {
       delay(3000)
             navController.popBackStack()
       navController.navigate(NavigationScreen.HomeScreen.route)
   }
   Scaffold(
       content = {
           Box(
               modifier = Modifier
                   .fillMaxSize()
                 .background(colorResource(R.color.purple_200))
           ) {
               Column(
                   modifier = Modifier
                       .align(Alignment.Center)
                       .padding(16.dp),
                   horizontalAlignment = Alignment.CenterHorizontally
               ) {
                   Image(
                       painter = painterResource(id = R.drawable.splash_img), // Replace with your image resource
                       contentDescription = null,


                       )


                   Spacer(modifier = Modifier.height(16.dp))
                   Text(
                       text = "Notes",
                       color = Color.White,
                       fontSize = 20.sp,
                       fontWeight = FontWeight.Bold,
                       textAlign = TextAlign.Center,
                   )
               }
               CircularProgressIndicator(
                   modifier = Modifier
                       .align(Alignment.BottomCenter)
                       .padding(36.dp),
                   color = colorResource(id = R.color.white)
               )
            }
       }
   )
}


				
			
4. Home Screen

After the splash screen, the user will automatically be redirected to the dashboard screen. Here, they will find a list of notes along with a prominent “+” button.

				
					@Composable
fun HomeScreenUI(context: Context, navController: NavHostController) {
   val list = SharePref.loadNotesFromSharedPreferences(context = context)
   list.reverse()
   Scaffold(
       topBar = {
           TopAppBar(
               title = {
                   Text(
                       text = "Notes",
                       fontSize = 20.sp,
                       fontWeight = FontWeight.Bold,
                       modifier = Modifier.fillMaxWidth(),
                       textAlign = TextAlign.Center
                   )
               })
       },
       content = {
           Column(
               modifier = Modifier
                   .fillMaxSize()
                   .padding(it)
           ) {
               LazyColumn(
                   modifier = Modifier
                       .weight(1f)
                       .padding(8.dp)
                       .fillMaxWidth(),
               ) {
                   itemsIndexed(list) { index, item ->
                       val itemColor = getColorForPosition(index)
                       ItemRow(item = item, itemColor){
                           val intent = Intent(context, ShowNotesScreen::class.java)
                           intent.putExtra("notes", item)
                           context.startActivity(intent)
                       }
                   }
               }


               Spacer(modifier = Modifier.height(8.dp))


           }
       },
       floatingActionButton = {
           FloatingActionButton(onClick = {
               navController.navigate(NavigationScreen.CreateNotesScreen.route)
           }, containerColor = colorResource(R.color.purple_500)) {
               Icon(
                   imageVector = Icons.Default.Add,
                   contentDescription = null,
                   tint = Color.White
               )
           }


       }


   )
}


@Composable
fun ItemRow(item: NoteDO, itemColor: Int, onItemClick: (NoteDO) -> Unit) {
   // Define the layout for each item in the list
   Column(
       modifier = Modifier
           .fillMaxWidth()
           .background(Color.White)
           .padding(8.dp)
           .clickable {
               onItemClick(item)
           }
   ) {
       Card(
           modifier = Modifier
               .fillMaxWidth()
               ,
           shape = RoundedCornerShape(8.dp),


           ) {
           Box(
               modifier = Modifier
                   .fillMaxSize()
                   .background(colorResource(id = itemColor)) // Set the background color here
           ) {
               Column(
                   modifier = Modifier
                       .fillMaxSize()
                       .padding(16.dp),
                   verticalArrangement = Arrangement.Center
               ) {
                   Text(
                       text = item.title,
                       fontSize = 18.sp,
                       fontWeight = FontWeight.Bold,
                       color = Color.Black, // Set the text color
                       modifier = Modifier.padding(bottom = 4.dp)
                   )
                   Row(
                       modifier = Modifier
                           .fillMaxWidth(),
                       verticalAlignment = Alignment.Bottom
                   ) {
                       Text(
                           text = item.description,
                           fontSize = 16.sp,
                           color = Color.Black.copy(alpha = 0.5f),
                           modifier = Modifier.weight(1f)
                       )
                       Text(
                           text = timestampToDateTime(item.createdON),
                           fontSize = 12.sp,
                           color = Color.Black,
                           fontWeight = FontWeight.Bold,
                       )
                   }


               }
           }


       }


   }
}


fun timestampToDateTime(timestamp: Long): String {
   // Create a SimpleDateFormat with the desired date format
   val sdf = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())


   // Convert the timestamp to a Date object
   val date = Date(timestamp)


   // Format the Date object as a string
   return sdf.format(date)
}


fun getColorForPosition(position: Int): Int {
   return if (position % 2 == 0) {
       R.color.card_1
   } else {
       R.color.card_2
   }
}

				
			
Adding a New Note & Saving

Notes Clicking on the “+” button will open a new screen dedicated to adding a new note. This screen will provide fields for both a title and a description. Additionally, a “Save” button will be included to store the entered note. When the user clicks on the “Save” button, the note’s details will be stored in shared preferences, ensuring that it is preserved for future access. By following these steps, you will have created a simple, yet functional notepad app, demonstrating the power and ease of Android Jetpack Compose for developing modern Android applications.

				
					@Composable
fun CreateNotesActivity(context: Context,navController: NavController) {
   Scaffold(
       topBar = {
           TopAppBar(
               title = {
                   Text(
                       text = "Create New Notes",
                       fontSize = 20.sp,
                       fontWeight = FontWeight.Bold,
                       modifier = Modifier.fillMaxWidth(),
                       textAlign = TextAlign.Center
                   )
               }
           )
       },
       content = {
           Column(
               modifier = Modifier
                   .fillMaxSize()
                   .padding(16.dp)
           ) {
               Text(text = "Title")
               Spacer(modifier = Modifier.height(8.dp))
               MyOutlinedTextField() {title,des->
                   if (title.isNotBlank() && des.isNotBlank()) {
                       val newNote = NoteDO(title, des,System.currentTimeMillis())
                       val list = SharePref.loadNotesFromSharedPreferences(context = context)
                       list.add(newNote)
                       SharePref.saveNotesToSharedPreferences(context,list)
                       navController.popBackStack()
                   }


               }




           }
       }


   )


}


@Composable
fun MyOutlinedTextField(onButtonClick: (String,String) -> Unit) {
   var title by remember { mutableStateOf("") }
   var description by remember { mutableStateOf("") }


   OutlinedTextField(
       value = title,
       onValueChange = {
           title = it
       },
       label = { Text(text = "Title") },
       modifier = Modifier
           .fillMaxWidth()
           .padding(16.dp)
   )


   OutlinedTextField(
       value = description,
       onValueChange = {
           description = it
       },
       label = { Text(text = "Description") },
       modifier = Modifier
           .fillMaxWidth()
           .padding(16.dp)
   )


   Button(
       onClick = {
           // Pass the entered text to the click handler
           onButtonClick(title,description)
       },
       modifier = Modifier
           .padding(16.dp)
           .fillMaxWidth(),


       colors = ButtonDefaults.buttonColors(colorResource(id = R.color.purple_500))




   ) {
       Text(text = "Submit")
   }
}

				
			

Table of Contents

Recent Comments
    December 2024
    M T W T F S S
     1
    2345678
    9101112131415
    16171819202122
    23242526272829
    3031  
    Tags:
    androidcoroutineskotlinmobile app development
    1 like
    Leave a Comment
    Share:
    Social