I am trying to implement a TextField which inputs an amount and formats it as soon as it is typed and also limits it to 100,000.
#Composable
fun MainScreen(
viewModel: MyViewModel
) {
val uiState by viewModel.uiState.collectAsState()
Column {
AmountSection(
uiState.amount,
viewModel::updateAmount
)
Text(text = viewModel.logs)
}
}
#Composable
fun AmountSection(
amount: TextFieldValue,
updateAmount: (TextFieldValue) -> Unit
) {
BasicTextField(
value = amount,
onValueChange = updateAmount,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number
)
)
MyViewModel:
class MyViewModel: ViewModel() {
private val _uiState = MutableStateFlow(MyUiState())
val uiState: StateFlow<MyUiState> = _uiState
var logs by mutableStateOf("")
var text = ""
fun updateAmount(amount: TextFieldValue) {
val formattedAmount: String = amount.text.getFormattedAmount()
text += "input = ${amount.text}\n"
text += "output = $formattedAmount \n"
logs = text
_uiState.update {
it.copy(amount = TextFieldValue(formattedAmount, TextRange(formattedAmount.length))
}
}
}
data class MyUiState(val amount: TextFieldValue = TextFieldValue())
(logs and text are just for logging purpose. Was finding it difficult to share the logcat output so presented it this way)
Result:
When I press 6, the input is "12,3456" which is expected (ignore the currency)
My getFormattedAmount() function removes the last six as ( 123456 > 100000). It outputs "12,345" which is also correct. "12,345" is what gets displayed on the screen.
But when I press 7, I get the input "12,34567". Where did that 6 come from?? It was not in uiState.amount.
(Please ignore the last output line. getFormattedAmount only removes the last character if the amount exceeds the limit and it gave wrong output because it didn't expect that input)
I feel that I making some really silly mistake here and would be really thankful if somecome could help me find that out.
Edit based on the edit:-
From the looks of the question, it isn't much clear what you wish to achieve here, but this is my deduction -
You just want a TextField that allows numbers to be input, but only up to a maximum value (VALUE, not characters). When a digit-press by a user leads to the value exceeding your max value, you want that digit to be not entered of course, but you wish to reflect no changes at all in this case, i.e., the field value should remain intact.
Based on the above deduction, here is an example:-
First of all, f your uiState variable. I'm keeping it simple for the sake of clarity.
class VM: ViewModel(){
var fieldValue by mutableStateOf("")
fun onFieldUpdate(newValue){
if(newValue.toDouble() > 999999999999999)
return
else
fieldValue = newValue
}
}
#Composable
fun CrazyField(fieldValue: String, onFieldUpdate: (String) -> Unit){
TextField(value = fieldValue, onValueChange = onFieldUpdate)
}
Do not comment further without actually running this.
Original answer:-
Use a doubles parser.
var text by remember { mutableStateOf("") }
TextField(
value = text,
onValueChange = {
if (it.toDouble() <= 100000)
text = it //Based on your use-case - it won't cut off text or limit the amount of characters
else text = it.subString(0,7) //In-case of pasting or fast typing
},
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
)
Found this comment on Compose slack channel by Sean.
As a model, you should assume that the keyboard may make aribitrary and large
edits each onValueChange. This may happen, for example, if the user uses
autocorrect, replaces a word with an emoji, or other smart editing features. To
correctly handle this, write any transformation logic with the assumption that
the current text passed to onValueChange is unrelated to the previous or next
values that will be passed to onValueChange.
So this is some issue with TextField & IME relationship.
I rewrote my getFormattedAmount function to format the given string without any assumptions (earlier it was assuming that amount is formatted till the last second character). Everything seems fixed now.
Related
I want to achieve the following use case: A payment flow where you start with a screen to enter the amount (AmountScreen) to pay and some other screens to enter other values for the payment. At the end of the flow, a summary screen (SummaryScreen) is shown where you can modify the values inline. For the sake of simplicity we will assume there is only AmountScreen followed by SummaryScreen.
Now the following requirements should be realized:
on AmountScreen you don't loose your input on configuration change
when changing a value in SummaryScreen and go back to AmountScreen (using system back), the input is set to the changed value
AmountScreen and SummaryScreen must not know about the viewModel of the payment flow (PaymentFlowViewModel, see below)
So the general problem is: we have a screen with an initial value for an input field. The initial value can be changed on another (later) screen and when navigating back to the first screen, the initial value should be set to the changed value.
I tried various approaches to achieve this without reverting to Kotlin flows (or LiveData). Is there an approach without flows to achieve this (I am quite new to compose so I might be overlooking something obvious). If flows is the correct approach, would I keep a MutableStateFlow inside the PaymentFlowViewModel for amount instead of a simple string?
Here is the approach I tried (stripped and simplified from the real world example).
General setup:
internal class PaymentFlowViewModel : ViewModel() {
var amount: String = ""
}
#Composable
internal fun NavigationGraph(viewModel: PaymentFlowViewModel = viewModel()) {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = "AMOUNT_INPUT_SCREEN"
) {
composable("AMOUNT_INPUT_SCREEN") {
AmountInputRoute(
// called when the Continue button is clicked
onAmountConfirmed = {
viewModel.amount = it
navController.navigate("SUMMARY_SCREEN")
},
// apply the entered amount as the initial value for the input text
initialAmount = viewModel.amount
)
}
composable("SUMMARY_SCREEN") {
SummaryRoute(
// called when the amount is changed inline
onAmountChanged = {
viewModel.amount = it
},
// apply the entered amount as the initial value for the input text
amount = viewModel.amount
)
}
}
}
The classes of the AmountScreen look like this:
#Composable
internal fun AmountInputRoute(
initialAmount: String,
onAmountConfirmed: (String) -> Unit
) {
// without the "LaunchedEffect" statement below this fulfils all requirements
// except that the changed value from the SummaryScreen is not applied
val amountInputState: MutableState<String> = rememberSaveable { mutableStateOf(initialAmount) }
// inserting this fulfils the req. that the changed value from SummaryScreen is
// applied, but breaks keeping the entered value on configuration change
LaunchedEffect(Unit) {
amountInputState.value = initialAmount
}
Column {
AmountInputView(
amountInput = amountInputState.value,
onAmountChange = { amountInput ->
amountInputState.value = amountInput
}
)
Button(onClick = { onAmountConfirmed(amountInputState.value) }) {
Text(text = "Continue")
}
}
}
```
I achieved the goal with a quite complicated approach - I would think there are better alternatives out there.
What I tried that did not work: using rememberSaveable passing initialAmount as parameter for inputs. Theoretically rememberSaveable would reinitialize its value when inputs changes, but apparently this does not happen when the composable is only on the back stack and also is not executed when it gets restored from the back stack.
What I implemented that did work:
#Composable
internal fun AmountInputRoute(
initialAmount:String,
onAmountConfirmed: (String) -> Unit
) {
var changedAmount by rememberSaveable {
mutableStateOf<String?>(null)
}
val amountInput by derivedStateOf {
if (changedAmount != null)
changedAmount
else
initialAmount
}
AmountInputView(
amountInput = amountInput,
onContinueClicked = {
onAmountConfirmed(amountInput)
changedAmount = null
},
validAmountChanged = {
changedAmount = it
}
)
}
Any better ideas?
I am trying to use state hoisting in android
I am new to android development using jetpack compose
onSearchChange: (String) -> Unit,
onCategoryChange: (Category) -> Unit,
onProductSelect: (Product) -> Unit,
composable(Screen.Home.route) { MainPage(navController = navController, searchQuery = "",
productCategories = categories, selectedCategory = Category("","",0),
products = pros, /* what do I write here for the 3 lines above?? :( the onSearch,etc I have an error bc of them */
)}
In addition to the answer, apologies, this is a bit long, as Ill try to share how I design my "state hoisting"
Lets simply start first with the following:
A: First based on the Official Docs
State in an app is any value that can change over time. This is a very
broad definition and encompasses everything from a Room database to a
variable on a class.
All Android apps display state to the user. A few examples of state in
Android apps:
A Snackbar that shows when a network connection can't be established.
A blog post and associated comments.
Ripple animations on buttons that
play when a user clicks them.
Stickers that a user can draw on top of
an image.
B: And personally, for me
"State Hoisting" is part of "State Management"
Now consider a very simple scenario, We have a LoginForm with 2 input fields, and have its basic states like the following
Input will be received from the user and will be stored in a mutableState variable named userName
Input will be received from the user and will be stored in a mutableState variable named password
We have defined 2 requirements above, without doing them, our LoginForm would be stateless
#Composable
fun LoginForm() {
var userName by remember { mutableStateOf("")}
var password by remember { mutableStateOf("") }
Column(
modifier = Modifier
.fillMaxWidth()
.wrapContentSize()
) {
TextField(
value = userName,
onValueChange = {
userName = it
}
)
TextField(
value = password,
onValueChange = {
password = it
},
visualTransformation = PasswordVisualTransformation()
)
}
}
So far, everything is working but nothing is "Hoisted", their states are handled inside the LoginForm composable.
State Hoisting Part 1: a LoginState class
Now apart from the 2 requirements above, lets add one additional requirement.
Validate user name and password
if login is invalid, show Toast "Sorry invalid login"
if login is valid, show Toast "Hello and Welcome to compose world"
This can be done inside the LoginForm composable, but its better to do the logic handling or any business logic in a separate class, leaving your UI intact independent of it
class LoginState {
var userName by mutableStateOf("")
var password by mutableStateOf("")
fun validateAction() {
if (userName == "Stack" && password == "Overflow") {
// tell the ui to show Toast
} else {
// tell the ui to show Toast
}
}
}
#Composable
fun LoginForm() {
val loginState = remember { LoginState() }
Column(
modifier = Modifier
.fillMaxWidth()
.wrapContentSize()
) {
TextField(
value = loginState.userName,
onValueChange = {
loginState.userName = it
}
)
TextField(
value = loginState.password,
onValueChange = {
loginState.password = it
},
visualTransformation = PasswordVisualTransformation()
)
}
}
Now everything is still working and with additional class where we hoisted our userName and password, and we included a validation functionality, nothing fancy, it will simply call something that will show Toast with a string message depending if the login is valid or not.
State Hoisting Part 2: a LoginViewModel class
Now apart from the 3 requirements above, lets add some more realistic requirements
Validate user name and password
if login is invalid, show Toast "Sorry invalid login"
if login is valid, call a Post login network call and update your database
if Login is success from backend sever show a Toast "Welcome To World"
But when the app is minimized you have to dispose any current network call, no Toast should be shown.
Take note that the codes below won't simply work and not how you would define it in a real situation though.
val viewModel = LoginViewModel()
data class UserLogin(
val userName : String = "",
val password : String = ""
)
class LoginViewModel (
val loginRepository: LoginRepository
) {
private val _loginFlow = MutableStateFlow(UserLogin())
val loginFlow : StateFlow<UserLogin> = _loginFlow
fun validateAction() {
// ommited codes
}
fun onUserNameInput(userName: String) {
}
fun onPasswordInput(password: String) {
}
}
#Composable
fun LoginForm() {
val loginState by viewModel.loginFlow.collectAsStateWithLifecycle()
Column(
modifier = Modifier
.fillMaxWidth()
.wrapContentSize()
) {
TextField(
value = loginState.userName,
onValueChange = {
viewModel.onUserNameInput(it)
}
)
TextField(
value = loginState.password,
onValueChange = {
viewModel.onPasswordInput(it)
},
visualTransformation = PasswordVisualTransformation()
)
}
}
But that's the most top level state hoisting you can do where you would deal with network calls and database.
To summarize:
You don't need to consider hoisting up your mutableStates if its just a simple composable doing simple thing.
But If the logic gets bigger consider using a State Class like the LoginState class to make your UI independent of the business logic.
If you have to perform some network calls, database updates and making sure such use-cases are bound to a LifeCycle, consider using a ViewModel
Another thing to mention but out of topic is when you are hoisting states, there is a thing called scoped re-composition where you want a specific composable to get updated without affecting the others around, it is where you will think your composable designs on how you would handle mutableStates.
To put it into simple terms, state hoisting is having your state variables in the outer most composable possible, this gives you access to said states in multiple functions, better performance, less mess and code reusability!
Hoisting is one of the fundamentals of using Jetpack Compose, example below:
#Composable
fun OuterComposable(
modifier: Modifier = Modifier
) {
// This is your state variable
var input by remember { mutabelStateOf("") }
InnerComposable(
modifier = Modifier,
text = input,
onType = { input = it } // This will asign the string returned by said function to the "input" state variable
)
}
#Composable
fun InnerComposable(
modifier: Modifier = Modifier
text: String,
onType: (String) -> Unit
) {
TextField(
modifier = modifier,
value = text,
onValueChange = { onType(it) } // This returns what the user typed (function mentioned in the previous comment)
)
}
With the code above, you have a text field in the "InnerComposable" function which becomes usable in multiple places with different values.
You can keep adding layers of composables, important thing is to keep the state variable in the outermost function possible.
Hope the explanation was clear! :)
I'm trying to write some test cases for my compose functions.
I have an outlined Text field with a maximum value of 16 characters.
So I want to test this feature. Here is the test:
#Test
fun checkMaxTaxCodeLength_16Character() {
val taxCode = composeRule.onNodeWithTag(testTag = AUTHENTICATION_SCREEN_TAX_CODE_EDIT_TEXT)
for (i in 'A'..'Z')
taxCode.performTextInput(i.toString())
taxCode.assertTextEquals("ABCDEFGHIJKLMNOP")
}
But although I can see the input is correct, the test fails, and it seems assertTextEquals doesn't work correctly. So:
first of all, what am I doing wrong?
Second, is there any way to, instead of checking the equality, check the text does not contain specific characters?
here is the code of text field:
OutlinedTextField(
value = state.taxCode,
maxLines = 1,
onValueChange = { string ->
viewModel.onEvent(
AuthenticationEvent.TaxCodeChanged(string)
)
},
label = {
Text(text = stringResource(id = R.string.tax_code))
},
modifier = Modifier
.fillMaxWidth()
.testTag(TestingConstant.AUTHENTICATION_SCREEN_TAX_CODE_EDIT_TEXT)
)
The maximum length is handled in the view model. If the user adds more characters than 16, the view model won't update the state and keep the old value.
first of all, what am I doing wrong?
assertTextEquals() takes the value of Text and EditableText in your semantics node combines them and then does a check against the values you pass in. The order does not matter, just make sure to pass in the value of the Text as one of the arguments.
val mNode = composeTestRule.onNodeWithText("Email"))
mNode.performTextInput("test#mail.com")
mNode.assertTextEquals("Email", "test#mail.com")
Please note the text Email is the label for the textfield composable.
To get the semantic information about your nodes you can have
#Test
fun print_semantics_tree() {
composeTestRule.onRoot(useUnmergedTree = true).printToLog(TAG)
}
For the TAG you can use any string. After running the above test you can search the logcat with the specified TAG. You should see something like
|-Node #3 at (l=155.0, t=105.0, r=925.0, b=259.0)px
| Focused = 'false'
| ImeAction = 'Default'
| EditableText = 'test#mail.com'
| TextSelectionRange = 'TextRange(0, 0)'
| Text = '[Email]'
| Actions = [RequestFocus, GetTextLayoutResult, SetText, SetSelection,
OnClick, OnLongClick, PasteText]
Please note you can also obtain the semantics node object with an index operation rather than iterating through all the values.
val value = fetchSemanticsNode().config[EditableText]
assertEquals("test#mail.com", value.toString())
Ok, still, the problem is open, but I achieved what I wanted another way. I used semantic nodes to get what is in edit text and compared it with what it should be:
#Test
fun checkMaxTaxCodeLength_16Character() {
val taxCode = composeRule.onNodeWithTag(testTag = AUTHENTICATION_SCREEN_TAX_CODE_EDIT_TEXT)
for (i in 'A'..'Z')
taxCode.performTextInput(i.toString())
for ((key,value) in taxCode.fetchSemanticsNode().config)
if (key.name =="EditableText")
assertEquals("ABCDEFGHIJKLMNOP",value.toString())
}
I'm basically writing a small quiz game with android jetpack compose in which you've got a question displayed and a text field below, I wanted to implement a "hint" (which appears under the text field and shows more and more of the correct answer for every bad answer). After implementing it, it causes a recomposition which selects a new question. Thus a question arrives, is there a way to update just the "hint" part of the screen or is that impossible ? (this might sound stupid but maybe I've missed something and there is a way)
Thanks in advance for every comment :)
You can recompose any part of a UI (without recomposing the entire screen or unrelated parts of the screen) as long as you isolate that section and only apply state changes to those parts that you want updated. The value you apply to your hint text should come from a viewmodel that contains a mutable state variable containing the text you want to update the hint with:
class MyViewModel : ViewModel() {
var hintText = mutableStateOf("")
fun onTextFieldChange(answer: String) {
// Retrieve your hint text from whatever api handles the user's response.
hintText.value = processAnswer(answer)
}
}
#Composable
fun Question() {
val vm = MyViewModel()
var text by remember { mutableStateOf("") }
Column(modifier = Modifier.fillMaxWidth()) {
TextField(
value = text,
onValueChange = {
text = it
vm.onTextFieldChange(it)
},
label = { Text("Label") },
singleLine = true
)
HintText(vm = vm)
}
}
#Composable
fun HintText(
vm: MyViewModel
) {
Text(text = vm.hintText.value)
}
Recently I'm playing with Jetpack Compose and I noticed that the text may not show up in TextField.
So I have a ViewModel with Flow of ViewState.
In my Compose file, I have something similar to this:
#Composable
internal fun TestScreen() {
val state by viewModel.state.collectAsState()
TestScreen {
viewState = state,
actioner = { ... }
}
}
#Composable
private fun TestScreen(viewState: ViewState, actioner: () -> Unit) {
var name by remember {
mutableStateOf(
TextFieldValue(viewState.name)
)
}
Surface {
....
Column {
....
OutlinedTextField(
...
value = name,
onValueChange = { textFieldValue ->
name = textFieldValue
actioner(...)
}
)
}
}
}
the OutlineTextField will never show what's already inside viewState.name
However, if I change this:
var name by remember {
mutableStateOf(
TextFieldValue(viewState.name)
)
}
To this:
var name = TextFieldValue(viewState.name)
Obviously it could show the value in viewState.name.
According to the Documentation (https://developer.android.com/jetpack/compose/state#state-in-composables) in which it recommends using remember & mutableStateOf to handle the changes.
I'll be very grateful if someone could help me to explain why the code with remember doesn't work but the directly assigned value worked?
EDIT
viewState.name is a String
and I "partially solved" this issue by doing the following:
var name by remember {
mutableStateOf(
TextFieldValue("")
)
}
name = TextFieldValue(viewState.name)
then the name can be shown. But it doesn't look quite right?
remember is used just to ensure that upon recomposition, the value of the mutableStateOf object does not get re-initialised to the initial value.
For example,
#Composable
fun Test1(){
var text by mutableStateOf ("Prev Text")
Text(text)
Button(onClick = { text = "Updated Text" }){
Text("Update The Text")
}
}
would not update the text on button click. This is because button click will change the mutableStateOf text, which will trigger a recomposition. However, when the control reaches the first line of the Composable, it will re-initialise the variable text to "Prev Text".
This is where remember comes in.
If you change the initialisation above to
var text by remember { mutableStateOf ("Prev Text") },
It wil tell compose to track this variable, and "remember" its value, and use it again on recomposition, when the control reaches the initialisation logic again. Hence, remember over there acts as a "guard" that does not let the control reach into the initialisation logic, and returns that latest remembered value of the variable it currently has in store.