Reputation: 65
please look at the code below:
class TextFieldComponent(
isSimpleInput: Boolean = false,
isEmailInput: Boolean = false,
isPasswordInput: Boolean= false){
@Composable
fun textInput(issimpleInput: Boolean, isEmailInput: Boolean, isPasswordInput: Boolean){
if(issimpleInput){
TextField(
// add colors, label, placeholder....etc
value ="this is a simple text field" ,
onValueChange = {} )
}
else if(isEmailInput){
TextField(
// add colors, label, placeholder....etc
value ="this is an email text field" ,
onValueChange = {} )
}
else if(isPasswordInput){
TextField(
// add colors, label, placeholder....etc
value ="this is an email text field" ,
onValueChange = {} )
}
}}
The code above is a small sample of a custom text field Composable I want to create to be reusable. It doesn't contain all the details, but you can imagine that it will include also the colours, borders, helper texts, labels that go with the app theme according to the text field type.
the code above (I guess) allows me to do the following:
var simpleTextInput = TextFieldComponent.textInput(isSimpleInput = true)
How do I modify the text so I can have the composable rendered when I instantiate the class: How do I modify the code above to be able to do the following:
var simpleTextInput = TextFieldComponent(isSimpleInput = true)
var emailInput = TextFieldComponent(isEmailInput = true)
var passwordInput = TextFieldComponent(isPasswordInput = true)
I tried to add this in init block but I struggled having a composable in it. could you please point me to the right direction.
Upvotes: 0
Views: 569
Reputation: 65
I kept the composable function only since the class doesn't add anything.
@Composable
fun TextInput(config: TextFieldComponent) {
if(config.isSimpleInput){
TextField(
// add colors, label, placeholder....etc
value ="this is a simple text field" ,
onValueChange = {} )
}
else if(config.isEmailInput){
TextField(
// add colors, label, placeholder....etc
value ="this is an email text field" ,
onValueChange = {} )
}
else if(config.isPasswordInput){
TextField(
// add colors, label, placeholder....etc
value ="this is an email text field" ,
onValueChange = {} )
}
}
Upvotes: 0
Reputation:
Move the textInput
function outside the class:
data class TextFieldComponent(
val isSimpleInput: Boolean = false,
val isEmailInput: Boolean = false,
val isPasswordInput: Boolean = false)
}
@Composable
fun textInput(config: TextFieldComponent) {
if(config.isSimpleInput){
TextField(
// add colors, label, placeholder....etc
value ="this is a simple text field" ,
onValueChange = {} )
}
else if(config.isEmailInput){
TextField(
// add colors, label, placeholder....etc
value ="this is an email text field" ,
onValueChange = {} )
}
else if(config.isPasswordInput){
TextField(
// add colors, label, placeholder....etc
value ="this is an email text field" ,
onValueChange = {} )
}
}
Now, you can manage your configuration for the fields separately from your UI.
Upvotes: 1