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.
@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)
}
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:
@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.
Before you begin, make sure you have the following:
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.
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:
sealed class NavigationScreen(val route:String)
{
object SplashScreen : NavigationScreen("splashScreen")
object HomeScreen : NavigationScreen("homeScreen")
object CreateNotesScreen : NavigationScreen("createNoteScreen")
}
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)
}
}
}
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)
)
}
}
)
}
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
}
}
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")
}
}
M | T | W | T | F | S | S |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
We are a team of artists. We provide professional services in the field of Mobile Applications, Web Applications and everything related to IT services. Turning to us for help once – you can no longer refuse.
© 2019 – 2022 | Made with ❤️ by App Ringer
Recent Comments