I am trying to bring some logic into a viewmodel for checking some data on a form.
I would need to report to a viewmodel (a special one just to check the validity of forms) each time the image has been changed.
For the TexField I was able to wire it up to the viewmodel by using the onProdNameChanged, but for the image I would not know how to notify it.
The viewmodel just checks the state of these fields on this form as well as other forms and it gives an OK as to enable a big button to create the product. How would you notify the Viewmodel that the image just changed ?
@Composable
fun name_and_Picture(productName: String,
onProdNameChanged: (String) - > Unit, ) {
Row(
modifier = Modifier
.background(color = colorResource(R.color.light_blue))
.padding(10. dp),
) {
val imageUri: MutableState < String > = rememberSaveable {
mutableStateOf("")
}
val painter = rememberAsyncImagePainter(model = imageUri.value.ifEmpty {
R.drawable.noimage150x150
})
val launcher =
rememberLauncherForActivityResult(contract = ActivityResultContracts.GetContent(),
onResult = {
uri: Uri ? - >
if (uri != null) {
imageUri.value = uri.toString()
val orignal_bitmap = MediaStore.Images.Media.getBitmap(requireActivity().getContentResolver(), uri)
Log.d(TAG, "Image processing original_width=${orignal_bitmap.width} + original_height=${orignal_bitmap.height}")
val cropped_bitmap = cropCenter(orignal_bitmap) !!
Log.d(TAG, "Image processing cropped_width=${cropped_bitmap.width} + cropped_height=${cropped_bitmap.height}")
val scaled_bitmap: Bitmap = cropped_bitmap.scale(150, 150, true)
Log.d(TAG, "Image processing scaled_width=${scaled_bitmap.width} + scaled_height=${scaled_bitmap.height}")
encodedBtmp = encodeToBase64(scaled_bitmap, Bitmap.CompressFormat.JPEG)
Log.d(TAG, "URI image = $uri")
editedByUser = true
} else
Log.d(TAG, "not a valid URI for Image")
})
var product_name_error by remember {
mutableStateOf(false)
}
Image(
painter = painter,
contentDescription = "Choose the image",
modifier = Modifier
.width(100. dp)
.height(100. dp)
.clickable {
launcher.launch("image/*")
}
)
BasicTextField(
// for inputs
modifier = Modifier.align(Alignment.Top)
.widthIn(10. dp, 10. dp),
value = "*",
singleLine = true,
textStyle = TextStyle(fontSize = 15. sp),
readOnly = true,
onValueChange = {},
) //
//Spacer(modifier = Modifier.width(10.dp))
TextField( // for inputs
value = productName,
//modifier = Modifier.border( width = 1.dp ),
isError = product_name_error,
singleLine = true,
onValueChange = onProdNameChanged,
label = {
Text("Product name*")
}
)
}
}
The complete code of the entire class is at https://github.com/hotellinawebmaster/newproduct.git
rememberAsyncImagePainter is provided by Coil images libary.
I looked everywhere but I do not have the slightest idea on how to achieve this.