How to add drawable's next to textfield in jetpack compose? - android

I am trying to figure out how to add a drawable to a text within a textfield (OutlinedTextField) but without any success. I have already created a drawable in the drawable folder. Do I need to create a seperate composable to insert it or can I directly add it inside the textfield ?
This is my textfield in the composable:
Spacer(modifier = Modifier.height(20.dp))
OutlinedTextField(
value = username.value,
onValueChange = { newText ->
username.value = newText
},
label = { Text(text = "Username") },
placeholder = { Text("") }, // placeholder / hint
modifier = Modifier
.fillMaxWidth(180F)
)

Use leadingIcon instead of placeHolder
OutlinedTextField(
value = username.value,
onValueChange = { newText ->
username.value = newText
},
label = { Text(text = "Username") },
leadingIcon = { Icon(imageVector = Icons.Default.Place, contentDescription = null)},
modifier = Modifier
.fillMaxWidth(180F)
)

Related

Cannot calculate specific dimensions for composable TextField

I am trying to create multiple items to encapsulate the specific behavior of every component but I cannot specify the dimensions for every view.
I want a Textfield with an X icon on its right
setContent {
Surface(
modifier = Modifier
.fillMaxSize()
.background(color = white)
.padding(horizontal = 15.dp)
) {
Row(horizontalArrangement = Arrangement.spacedBy(15.dp)) {
Searcher(
modifier = Modifier.weight(1f),
onTextChanged = { },
onSearchAction = { }
)
Image(
painter = painterResource(id = R.drawable.ic_close),
contentDescription = null,
colorFilter = ColorFilter.tint(blue)
)
}
}
}
The component is the following
#Composable
fun Searcher(
modifier: Modifier = Modifier,
onTextChanged: (String) -> Unit,
onSearchAction: () -> Unit
) {
Row {
SearcherField(
onTextChanged = onTextChanged,
onSearchAction = onSearchAction,
modifier = Modifier.weight(1f)
)
CircularSearch(
modifier = Modifier
.padding(horizontal = 10.dp)
.align(CenterVertically)
)
}
}
and the SearcherField:
#Composable
fun SearcherField(
modifier: Modifier = Modifier,
onTextChanged: (String) -> Unit,
onSearchAction: () -> Unit
) {
var fieldText by remember { mutableStateOf(emptyText) }
TextField(
value = fieldText,
onValueChange = { value ->
fieldText = value
if (value.length > 2)
onTextChanged(value)
},
singleLine = true,
textStyle = Typography.h5.copy(color = White),
colors = TextFieldDefaults.textFieldColors(
cursorColor = White,
focusedIndicatorColor = Transparent,
unfocusedIndicatorColor = Transparent,
backgroundColor = Transparent
),
trailingIcon = {
if (fieldText.isNotEmpty()) {
IconButton(onClick = {
fieldText = emptyText
}) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = emptyText
)
}
}
},
placeholder = {
Text(
text = stringResource(id = R.string.dondebuscas),
style = Typography.h5.copy(color = White)
)
},
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(
onSearch = {
onSearchAction()
}
),
modifier = modifier.fillMaxWidth()
)
}
But I don´t know why, but the component Searcher with the placeholder is rendered in two lines.
It´s all about the placeholder that seems to be resized for not having enough space because if I remove the placeholder, the component looks perfect.
Everything is in one line, not having a placeholder of two lines. I m trying to modify the size of every item but I am not able to get the expected result and I don´t know if the problem is just about the placeholder.
How can I solve it? UPDATE -> I found the error
Thanks in advance!
Add maxlines = 1 to the placeholder Text's parameters.
Your field is single -lune but your text is multi-line. I think it creates conflict in implementation.
Okay... I find that the problem is about the trailing icon. Is not visible when there is no text in the TextField but is still occupying some space in the view, that´s why the placeholder cannot occupy the entire space. The solution is the following.
val trailingIconView = #Composable {
IconButton(onClick = {
fieldText = emptyText
}) {
Icon(
imageVector = Icons.Default.Close,
contentDescription = emptyText
)
}
}
Create a variable with the icon and set it to the TextField only when is required
trailingIcon = if (fieldText.isNotEmpty()) trailingIconView else null,
With that, the trailing icon will be "gone" instead of "invisible" (the old way).
Still have a lot to learn.

None if the following functions can be called with the Arguments supplied Jetpack Compose Error

I keep getting this error whenever I try to use a textfield in Compose, I have tried both Textfield implementations, ie one with a String value and TextFieldValue arguments but still get the error, I have also tried using
var text = rememberSaveable{mutableStateOf("")}
and
var text by remember {mutableStateOf("")}. I have also tried hoisting the State which is what I wanted to do in the first place but still get the error
Here's the code
fun SearchAppBar(
query: String,
onQueryChanged: (String) -> Unit,
onExecuteSearch: () -> Unit,
scrollPosition: Int,
selectedCategory: FoodCategory?,
onSelectedCategoryChanged: (String) -> Unit,
onCategoryChangePosition: (Int) -> Unit,
) {
Surface(
modifier = Modifier.fillMaxWidth(),
color = Color.White,
elevation = 8.dp,
) {
Column {
Row(
modifier = Modifier.fillMaxWidth(),
) {
TextField(
modifier = Modifier
.fillMaxWidth(.9f)
.padding(8.dp),
value = query,
onValueChange = {
onQueryChanged(it)
},
label = {
Text(text = "Search")
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
imeAction = ImeAction.Done,
),
leadingIcon = {
Icon(Icons.Filled.Search)
},
onImeActionPerformed = { action, softKeyboardController ->
if (action == ImeAction.Done) {
onExecuteSearch()
softKeyboardController?.hideSoftwareKeyboard()
}
},
textStyle = TextStyle(color = MaterialTheme.colors.onSurface),
backgroundColor = MaterialTheme.colors.surface
)
}
val scrollState = rememberScrollState()
val scope = rememberCoroutineScope()
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 8.dp, bottom = 8.dp)
.horizontalScroll(scrollState)
) {
scope.launch {
scrollState.scrollTo(
scrollPosition
)
}
for (category in getAllFoodCategories()) {
FoodCategoryChip(
category = category.value,
isSelected = selectedCategory == category,
onSelectedCategoryChanged = {
onSelectedCategoryChanged(it)
onCategoryChangePosition(
getAllFoodCategories().indexOf(selectedCategory)
)
},
onExecuteSearch = {
onExecuteSearch()
}
)
}
}
}
}
}
You can only use the combination of parameters contained in only one of the implementations. You can't, for example, use keyboardOptions alongside onImeActionPerformed.
Turns out the backgroundColor property isnt valid anymore, use colors:. Also as pointed out by Richard Onslow Roper in his answer, look through the constructor of the TextField and see which properties are not part of your the Version of TextField you want to use
Don't do
TextField(
value = query,
onValueChange = {
onQueryChanged(it)
},
label = {
Text(text = "Search")
},
backgroundColor = MaterialTheme.colors.surface
)
do this instead
TextField(
value = query,
onValueChange = {
onQueryChanged(it)
},
label = {
Text(text = "Search")
},
colors= TextFieldDefaults.textFieldColors(
backgroundColor = MaterialTheme.colors.surface
)
)

How to clear textfield value in Jetpack Compose?

I've developed a textInput composable with a trailing icon, and I'd like to clear the textInput when the icon is clicked. How can I access the textInput value, so that I can clear it?
#Composable
fun TextInput(
myVal: String,
label: String,
placeholder: String="",
helperText: String="",
errorText: String="",
onValueChange : (String) -> Unit){
val hasError = !errorText.isNullOrEmpty()
val helperColor = if (hasError)
Color(0xFFfe392f)
else
Color(0xFF5c6a79)
Row() {
Column() {
TextField(
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent,
textColor = Color(0xFF011e41),
cursorColor = Color(0xFF011e41),
focusedLabelColor = Color(0xFF011e41),
unfocusedLabelColor = Color(0xFF011e41),
unfocusedIndicatorColor = Color(0xFFebeced),
focusedIndicatorColor = Color(0xFF011e41),
errorCursorColor = Color(0xFFfe392f),
errorIndicatorColor = Color(0xFFfe392f),
errorLabelColor = Color(0xFFfe392f)
),
value = myVal,
onValueChange = onValueChange,
label = { Text(label) },
placeholder = { Text(placeholder) },
isError = hasError,
trailingIcon = {Icon(Icons.Filled.Email, contentDescription = "sdsd", modifier = Modifier.offset(x= 10.dp).clickable {
//What should I do here?
})}
)
Text(
modifier = Modifier.padding(8.dp),
text = if (hasError) errorText else helperText,
fontSize = 12.sp,
color = helperColor,
)
}
}
}
it's used like this:
var text by remember { mutableStateOf("") }
TextInput(myVal = text, label = "label", helperText = "", errorText = "my error") {text = it}
You can use the trailingIcon attribute with a custom clickable modifier.
Something like:
var text by rememberSaveable { mutableStateOf("") }
TextField(
value = text,
onValueChange = { text = it },
trailingIcon = {
Icon(Icons.Default.Clear,
contentDescription = "clear text",
modifier = Modifier
.clickable {
text = ""
}
)
}
)
If you are using a TextFieldValue:
val content = "content"
var text by rememberSaveable(stateSaver = TextFieldValue.Saver) {
mutableStateOf(TextFieldValue(content))
}
TextField(
value = text,
onValueChange = { text = it },
trailingIcon = {
Icon(Icons.Default.Clear,
contentDescription = "clear text",
modifier = Modifier
.clickable {
text = TextFieldValue("")
}
)
}
)
the click handler of your trailing icon has to call the TextField's onValueChange with an empty string:
...
trailingIcon = {
Icon(
Icons.Filled.Email,
contentDescription = "sdsd",
modifier = Modifier
.offset(x= 10.dp)
.clickable {
//just send an update that the field is now empty
onValueChange("")
}
)
}
...
Use trailingIcon Composable property with IconButton to match the background selector of the icon with the rest of the theme. You can also put empty condition to display it only when there is some input in the text field.
Below is sample code snippet:
var text by remember { mutableStateOf ("") }
TextField(
trailingIcon = {
when {
text.isNotEmpty() -> IconButton(onClick = {
text = ""
}) {
Icon(
imageVector = Icons.Filled.Clear,
contentDescription = "Clear"
)
}
}
}
)
This shall achieve this
//Caller
val text by remember { mutableStateOf (...) }
TextInput(text, ..., ...,)
//Composable
#Composable
fun TextInput(text, ..., ...){
val textState by remember { mutableStateOf (text) }
TextField(
value = textState,
trailingIcon = {
Icon(..., Modifier.clickable { textState = "" })
}
}

Dynamically add views on click of Button using Jetpack Compose

I want to dynamically add Text Fields to my layout everytime user click "Add" button.Added Text Field should be added above "Add" button .i.e.between Step 1 TextField and Add Button.How can this be achieved through Jetpack Compose?Below is screenshot followed by my current code..
Code-
Column(modifier = Modifier.padding(16.dp)) {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = step1,
onValueChange = {
viewModel.onStep1Changed(it)
},
label = {
Text(text = "Step 1...")
},
shape = RoundedCornerShape(8.dp),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent),
trailingIcon = {
Icon(
modifier = Modifier.padding(start=10.dp),
imageVector = Icons.Filled.Image,
tint= Color.Blue,
contentDescription = "Select Image"
)
}
)
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = {
//TODO Dynamically add text fields
}){
Text("Add")
}
}
Column(modifier = Modifier.padding(16.dp)) {
val textFieldCount by remember { mutableStateOf (1) }
repeat(textFieldCount) {
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = step1,
onValueChange = {
viewModel.onStep1Changed(it)
},
label = {
Text(text = "Step 1...")
},
shape = RoundedCornerShape(8.dp),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent),
trailingIcon = {
Icon(
modifier = Modifier.padding(start=10.dp),
imageVector = Icons.Filled.Image,
tint= Color.Blue,
contentDescription = "Select Image"
)
}
)
Spacer(modifier = Modifier.height(16.dp))
}
Button(onClick = {
textFieldCount++
}){
Text("Add")
}
}

drawableStart equivalent in TextField of Jetpack compose

So I was checking out this document here https://developer.android.com/jetpack/compose/text#enter-modify-text
I have managed to create a text field (EditText) Using:
#Composable
fun EmailField() {
var text by remember { mutableStateOf("") }
TextField(
colors = TextFieldDefaults.textFieldColors(
textColor = Color.White,
focusedIndicatorColor = Color.White,
focusedLabelColor = Color.White
),
value = text,
onValueChange = { text = it },
label = { Text("Email") }
)
}
Now I want to set the drawableStart which we had in XML. So is there any such equivalent or other way to achieve?
I want to create something like this:
Any help or lead is appreciated
You can use the leadingIcon attribute:
TextField(
value = text,
onValueChange = { text = it },
leadingIcon = {
Icon(Icons.Filled.Email,
"contentDescription",
modifier = Modifier.clickable { /* .. */})}
)

Categories

Resources