Step 1 :-
Paste this code in diffrent format
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchBar(
query: String,
onQueryChange: (String) -> Unit,
onSearch: (String) -> Unit,
onClearQuery: () -> Unit,
modifier: Modifier = Modifier
) {
TextField(
value = query,
onValueChange = onQueryChange,
placeholder = {
Text(text = "Search here...", color = Color.Gray)
},
modifier = modifier.fillMaxWidth(),
leadingIcon = {
Icon(imageVector = Icons.Filled.Search, contentDescription = "Search Icon")
},
trailingIcon = {
if (query.isNotEmpty()) {
IconButton(onClick = onClearQuery) {
Icon(imageVector = Icons.Filled.Close, contentDescription = "Clear Icon")
}
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(
onSearch = {
onSearch(query)
}
),
colors = TextFieldDefaults.textFieldColors(
containerColor = Color.Transparent,
cursorColor = MaterialTheme.colorScheme.primary,
focusedIndicatorColor = MaterialTheme.colorScheme.primary,
unfocusedIndicatorColor = Color.Gray
)
)
}
@Composable
fun SearchScreen() {
var searchQuery by remember { mutableStateOf("") }
Scaffold(
topBar = {
SearchBar(
query = searchQuery,
onQueryChange = { searchQuery = it },
onSearch = { query ->
// Handle search action here
println("Searching for $query")
},
onClearQuery = { searchQuery = "" }
)
}
) { contentPadding ->
// Properly handle the content padding passed by the Scaffold
Box(modifier = Modifier.padding(contentPadding)) {
// Your actual content goes here
Text(text = "Search results will appear here", modifier = Modifier.padding(16.dp))
}
}
}
@Preview(showBackground = true)
@Composable
fun SearchScreenPreview() {
SearchScreen()
}
0 Comments