Home > front end >  How to display Toast.makeText result in another page textView using kotlin
How to display Toast.makeText result in another page textView using kotlin

Time:04-08

//This is my scanner barcode code using kotlin

override fun receiveDetections(detections: Detector.Detections) {

            val barcodes = detections.detectedItems
            if (barcodes.size() == 1) {
                scannedValue = barcodes.valueAt(0).rawValue
                runOnUiThread {
                    cameraSource.stop()
                    Toast.makeText(this@InsertStockInActivity, "value- $scannedValue", Toast.LENGTH_SHORT).show()
                    finish()
                }
            }else
            {
                Toast.makeText(this@InsertStockInActivity, "value- else", Toast.LENGTH_SHORT).show()

            }
        }

//This is my input page

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    binding = FragmentInputStockInBinding.inflate(inflater, container, false)
    binding.btnScanBarcode.setOnClickListener{ nav.navigate(R.id.insertStockInActivity)}

    return binding.root
}[enter image description here][1]

CodePudding user response:

i thnk you should extract your toast text as a variable and pass it to another page ( i assume that your mean are to another fragment/activity or to another screen)


  private lateinit var toastText:String
  ...

  if (barcodes.size() == 1) {
    ...     
    toastText = scannedValue      
    ...
  } else {
    toastText = "value- else"
  }

  Toast.makeText(this@InsertStockInActivity, toastText , Toast.LENGTH_SHORT).show()

}

and pass toastText to another page via Intent or safe-args if you are using Jetpack Navigation

CodePudding user response:

You could use a view model, live data, or another (static) object to hold your results in a variable. Along the same lines, you can create a show toast function in another class and just pass the context of the fragment or activity that you are in. For example a fragment context could be requireContext().

 fun showToast(context: Context?, message: String) {
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
  • Related