Certainly! Below is a comprehensive guide to developing the described Kotlin Android application. We'll use Jetpack Compose for modern and efficient UI development. The application will display numbered squares in a grid that adapts to screen orientation, with a button to add new squares. The state will be preserved across configuration changes using ViewModel.
Table of Contents
- Project Setup
- Defining Resources
- Creating the ViewModel
- Designing the UI with Jetpack Compose
- Handling Orientation Changes
- Final Code Structure
- Testing Scenarios
Project Setup
-
Create a New Android Project:
- Open Android Studio.
- Select "New Project".
- Choose "Empty Compose Activity".
- Configure project name, package, and other settings as desired.
- Ensure Kotlin is selected as the language.
-
Add Necessary Dependencies:
Jetpack Compose dependencies are typically included by default in a new Compose project. Ensure your build.gradle includes the latest Compose versions.
dependencies {
implementation "androidx.core:core-ktx:1.10.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.6.1"
implementation "androidx.activity:activity-compose:1.7.2"
implementation "androidx.compose.ui:ui:1.5.3"
implementation "androidx.compose.material:material:1.5.3"
implementation "androidx.compose.ui:ui-tooling-preview:1.5.3"
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1"
// Optional: For previews
debugImplementation "androidx.compose.ui:ui-tooling:1.5.3"
}
Sync your project after adding dependencies.
Defining Resources
To adhere to the requirement of avoiding hardcoding, define colors and dimensions in resource files.
-
Colors:
In res/values/colors.xml, define the required colors.
<resources>
<color name="red_background">#F44336</color>
<color name="blue_background">#2196F3</color>
<color name="white">#FFFFFF</color>
</resources>
-
Dimensions:
If needed, define sizes in res/values/dimens.xml.
<resources>
<dimen name="card_size">100dp</dimen>
<dimen name="card_margin">8dp</dimen>
<dimen name="button_height">56dp</dimen>
</resources>
-
Strings:
Define any strings in res/values/strings.xml.
<resources>
<string name="app_name">Numbered Squares</string>
<string name="add_button">Add</string>
</resources>
Creating the ViewModel
To preserve the state across configuration changes without using persistent storage, utilize ViewModel.
-
Create MainViewModel.kt:
package com.example.numberedsquares
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class MainViewModel : ViewModel() {
// Using MutableStateFlow to hold the list of indices
private val _items = MutableStateFlow<List<Int>>(emptyList())
val items: StateFlow<List<Int>> = _items
// Function to add a new item
fun addItem() {
val newItem = _items.value.size // Zero-based index
_items.value = _items.value + newItem
}
}
Explanation:
StateFlow is used to hold the list of items, ensuring state is preserved across configuration changes.
addItem() appends a new index to the list.
Designing the UI with Jetpack Compose
-
Update MainActivity.kt:
package com.example.numberedsquares
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.numberedsquares.ui.theme.NumberedSquaresTheme
class MainActivity : ComponentActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
NumberedSquaresTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainScreen(viewModel = viewModel)
}
}
}
}
}
@Composable
fun MainScreen(viewModel: MainViewModel) {
// Collect the list of items as state
val items by viewModel.items.collectAsState()
// Get current configuration to determine orientation
val configuration = LocalConfiguration.current
val isPortrait = configuration.orientation == Configuration.ORIENTATION_PORTRAIT
val columns = if (isPortrait) 3 else 4
// Scaffold to position the button
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = { viewModel.addItem() },
modifier = Modifier
.padding(16.dp),
content = {
Text("+")
}
)
},
isFloatingActionButtonDocked = false
) { paddingValues ->
// Adjust the content to avoid overlapping with the FAB
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
) {
// LazyVerticalGrid requires Compose version >= 1.2.0
LazyVerticalGrid(
columns = GridCells.Fixed(columns),
modifier = Modifier
.weight(1f)
.padding(8.dp)
) {
items(items) { index ->
NumberCard(index = index)
}
}
// Optional: Additional padding at the bottom
Spacer(modifier = Modifier.height(16.dp))
}
}
}
@Composable
fun NumberCard(index: Int) {
// Determine background color based on even/odd
val backgroundColor = if (index % 2 == 0) {
colorResource(id = R.color.red_background)
} else {
colorResource(id = R.color.blue_background)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(8.dp)
.aspectRatio(1f) // Makes the box square
.background(color = backgroundColor)
) {
Text(
text = (index + 1).toString(), // Displaying index starting from 1
color = colorResource(id = R.color.white),
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
}
}
Handling Orientation Changes
Using ViewModel with StateFlow ensures that the list of items persists across configuration changes like screen rotation. No additional handling is required as Compose and ViewModel work seamlessly together.
Final Code Structure
Project Structure:
app/
├─ src/
│ ├─ main/
│ │ ├─ java/com/example/numberedsquares/
│ │ │ ├─ MainActivity.kt
│ │ │ ├─ MainViewModel.kt
│ │ ├─ res/
│ │ │ ├─ values/
│ │ │ │ ├─ strings.xml
│ │ │ │ ├─ colors.xml
│ │ │ │ ├─ dimens.xml
│ ├─ AndroidManifest.xml
MainViewModel.kt:
package com.example.numberedsquares
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
class MainViewModel : ViewModel() {
private val _items = MutableStateFlow<List<Int>>(emptyList())
val items: StateFlow<List<Int>> = _items
fun addItem() {
val newItem = _items.value.size
_items.value = _items.value + newItem
}
}
MainActivity.kt:
package com.example.numberedsquares
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.GridCells
import androidx.compose.foundation.lazy.LazyVerticalGrid
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.numberedsquares.ui.theme.NumberedSquaresTheme
class MainActivity : ComponentActivity() {
private val viewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
NumberedSquaresTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
MainScreen(viewModel = viewModel)
}
}
}
}
}
@Composable
fun MainScreen(viewModel: MainViewModel) {
val items by viewModel.items.collectAsState()
val configuration = LocalConfiguration.current
val isPortrait = configuration.orientation == Configuration.ORIENTATION_PORTRAIT
val columns = if (isPortrait) 3 else 4
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = { viewModel.addItem() },
modifier = Modifier.padding(16.dp)
) {
Text("+")
}
},
isFloatingActionButtonDocked = false
) { paddingValues ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(paddingValues)
) {
LazyVerticalGrid(
columns = GridCells.Fixed(columns),
modifier = Modifier
.weight(1f)
.padding(8.dp)
) {
items(items) { index ->
NumberCard(index = index)
}
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
@Composable
fun NumberCard(index: Int) {
val backgroundColor = if (index % 2 == 0) {
colorResource(id = R.color.red_background)
} else {
colorResource(id = R.color.blue_background)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.padding(8.dp)
.aspectRatio(1f)
.background(color = backgroundColor)
) {
Text(
text = (index + 1).toString(),
color = colorResource(id = R.color.white),
fontSize = 24.sp,
fontWeight = FontWeight.Bold
)
}
}
res/values/colors.xml:
<resources>
<color name="red_background">#F44336</color>
<color name="blue_background">#2196F3</color>
<color name="white">#FFFFFF</color>
</resources>
res/values/strings.xml:
<resources>
<string name="app_name">Numbered Squares</string>
<string name="add_button">Add</string>
</resources>
res/values/dimens.xml:
<resources>
<dimen name="card_size">100dp</dimen>
<dimen name="card_margin">8dp</dimen>
<dimen name="button_height">56dp</dimen>
</resources>
Note: Ensure that ui.theme package contains necessary theme setup. The default Compose template includes it.
Testing Scenarios
-
Rotate Before Adding Any Squares:
- Launch the app.
- Rotate the device before clicking the Add button.
- The grid should adjust to 3 columns (portrait) or 4 columns (landscape) without any squares displayed.
-
Rotate After Adding Squares:
- Launch the app.
- Click the Add button multiple times to add squares.
- Rotate the device.
- The number of squares should remain intact, adjusting the grid layout based on orientation.
-
Add Squares After Rotation:
- Rotate the device first.
- Click the Add button to add squares.
- Verify that squares are added correctly with appropriate background colors.
-
No Overlapping of FAB and Squares:
- Ensure that the Floating Action Button (FAB) does not overlap any squares.
- Squares should adjust their positions accordingly.
-
Visual Confirmation:
- Even indices should have a red background with the number displayed in white.
- Odd indices should have a blue background with the number displayed in white.
-
Square Shape Verification:
- Each card should maintain a square shape regardless of screen size or orientation.
Additional Considerations
-
Accessibility:
- Add content descriptions if necessary.
- Ensure sufficient color contrast.
-
Performance:
- For a large number of squares, consider using efficient state management.
-
Enhancements:
- Animate the addition of squares.
- Provide visual feedback on button clicks.
By following the above steps, you'll have a robust Kotlin Android application that meets all the specified requirements without using persistent storage, internet access, or hardcoded values. The use of ViewModel ensures state preservation across configuration changes, and Jetpack Compose provides a flexible and modern UI framework to implement the responsive grid and interactive components.