Android “Only the original thread that created a view hierarchy can touch its views.”

后端 未结 28 3272
鱼传尺愫
鱼传尺愫 2020-11-21 04:44

I\'ve built a simple music player in Android. The view for each song contains a SeekBar, implemented like this:

public class Song extends Activity implement         


        
28条回答
  •  逝去的感伤
    2020-11-21 05:24

    If you are within a fragment, then you also need to get the activity object as runOnUIThread is a method on the activity.

    An example in Kotlin with some surrounding context to make it clearer - this example is navigating from a camera fragment to a gallery fragment:

    // Setup image capture listener which is triggered after photo has been taken
    imageCapture.takePicture(
           outputOptions, cameraExecutor, object : ImageCapture.OnImageSavedCallback {
    
               override fun onError(exc: ImageCaptureException) {
               Log.e(TAG, "Photo capture failed: ${exc.message}", exc)
            }
    
            override fun onImageSaved(output: ImageCapture.OutputFileResults) {
                            val savedUri = output.savedUri ?: Uri.fromFile(photoFile)
                            Log.d(TAG, "Photo capture succeeded: $savedUri")
                   
                 //Do whatever work you do when image is saved         
                 
                 //Now ask navigator to move to new tab - as this
                 //updates UI do on the UI thread           
                 activity?.runOnUiThread( {
                     Navigation.findNavController(
                            requireActivity(), R.id.fragment_container
                     ).navigate(CameraFragmentDirections
                            .actionCameraToGallery(outputDirectory.absolutePath))
                  })
    

提交回复
热议问题