android-fragments CameraFragment.kt与xml连接时出错

c9qzyr3d  于 2022-11-14  发布在  Android
关注(0)|答案(2)|浏览(134)

我需要帮助,请,我在fragment.kt中得到错误的过程中得到一个摄像头设置

**

//fragmentcamera.xml

**

  1. **<?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. xmlns:tools="http://schemas.android.com/tools"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. tools:context=".MainActivity">
  9. <androidx.camera.view.PreviewView
  10. android:layout_width="match_parent"
  11. android:layout_height="match_parent"
  12. android:id="@+id/preview"/>
  13. <Button
  14. android:id="@+id/btnTakePhoto"
  15. android:layout_width="wrap_content"
  16. android:layout_height="wrap_content"
  17. android:layout_margin="16dp"
  18. android:text="Take photo"
  19. app:layout_constraintStart_toStartOf="parent"
  20. app:layout_constraintEnd_toStartOf="@id/btnDisplayGallery"
  21. app:layout_constraintBottom_toBottomOf="parent"/>
  22. <Button
  23. android:id="@+id/btnDisplayGallery"
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:layout_margin="16dp"
  27. android:layout_marginBottom="300dp"
  28. android:text="Display gallery"
  29. app:layout_constraintBottom_toBottomOf="parent"
  30. app:layout_constraintEnd_toEndOf="parent"
  31. app:layout_constraintStart_toEndOf="@id/btnTakePhoto" />
  32. </androidx.constraintlayout.widget.ConstraintLayout>**

以下是camerafragment.kt的图像


指令集


指令集


s的数据结构
我得到的错误


指令集

ghhaqwfi

ghhaqwfi1#

  1. import android.Manifest
  2. import android.content.Intent
  3. import android.content.pm.PackageManager
  4. import android.graphics.Color
  5. import android.graphics.drawable.ColorDrawable
  6. import android.os.Bundle
  7. import android.util.Log
  8. import android.view.LayoutInflater
  9. import android.view.View
  10. import android.view.ViewGroup
  11. import android.widget.Button
  12. import android.widget.Toast
  13. import androidx.camera.core.CameraSelector
  14. import androidx.camera.core.ImageCapture
  15. import androidx.camera.core.ImageCaptureException
  16. import androidx.camera.core.Preview
  17. import androidx.camera.lifecycle.ProcessCameraProvider
  18. import androidx.camera.view.PreviewView
  19. import androidx.core.app.ActivityCompat
  20. import androidx.core.content.ContextCompat
  21. import androidx.core.net.toUri
  22. import androidx.fragment.app.Fragment
  23. import com.google.common.util.concurrent.ListenableFuture
  24. import java.io.File
  25. import java.util.concurrent.ExecutorService
  26. import java.util.concurrent.Executors
  27. class cameraFragment : Fragment() {
  28. // TODO: Rename and change types of parameters
  29. // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
  30. //ListenableFuture interface listens for async operations external to
  31. // main thread
  32. // requires type of activity being observed - ProcessCameraProvider
  33. private lateinit var cameraProviderFuture:
  34. ListenableFuture<ProcessCameraProvider>
  35. //used to decide whether to use front or back camera
  36. private lateinit var cameraSelector: CameraSelector
  37. //use case for capturing images
  38. private var imageCapture: ImageCapture? = null
  39. //interface that extends Executor to provide thread for capturing an image
  40. private lateinit var imgCaptureExecutor: ExecutorService
  41. //static variables
  42. companion object {
  43. //used for messages output in debugger
  44. val TAG = "cameraFragment"
  45. //used to check request code
  46. private var REQUEST_CODE = 101
  47. }
  48. override fun onCreateView(
  49. inflater: LayoutInflater, container: ViewGroup?,
  50. savedInstanceState: Bundle?
  51. ): View {
  52. // Inflate the layout for requireActivity() fragment
  53. val view: View = inflater.inflate(
  54. R.layout.xml_camera,
  55. container,
  56. false
  57. )
  58. //get instance of ProcessCameraProvider
  59. cameraProviderFuture = ProcessCameraProvider.getInstance(requireActivity())
  60. //set default to back camera
  61. cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
  62. //instantiate imgCaptureExecutor
  63. imgCaptureExecutor = Executors.newSingleThreadExecutor()
  64. //check for permissions (similar to other sensors)
  65. if (ActivityCompat.checkSelfPermission(
  66. requireActivity(),
  67. Manifest.permission.CAMERA
  68. ) != PackageManager.PERMISSION_GRANTED
  69. )
  70. //request permissions
  71. ActivityCompat.requestPermissions(
  72. requireActivity(),
  73. arrayOf(
  74. //array containing required permissions
  75. Manifest.permission.CAMERA
  76. ),
  77. REQUEST_CODE
  78. )
  79. else {
  80. //if permission already granted, start camera
  81. startCamera()
  82. }
  83. //set up event listener for btnCapture click
  84. val btnTakePhoto: Button = view.findViewById(R.id.btnTakePhoto)
  85. btnTakePhoto.setOnClickListener {
  86. takePhoto()
  87. } //set up event listener for btnGallery click
  88. val btnDisplayGallery: Button = view.findViewById(R.id.btnDisplayGallery)
  89. btnDisplayGallery.setOnClickListener {
  90. displayGallery()
  91. }
  92. return view
  93. }
  94. //invoked when permissions change
  95. override fun onRequestPermissionsResult(
  96. requestCode: Int,
  97. permissions: Array<out String>,
  98. grantResults: IntArray
  99. ) {
  100. super.onRequestPermissionsResult(requestCode, permissions, grantResults)
  101. //check that request code matches and permission granted
  102. if (requestCode == REQUEST_CODE &&
  103. grantResults.isNotEmpty() &&
  104. grantResults[0] == PackageManager.PERMISSION_GRANTED
  105. ) {
  106. //if permission now granted, start camera
  107. startCamera()
  108. }
  109. }
  110. //listen for data from camera
  111. private fun startCamera() {
  112. cameraProviderFuture.addListener(
  113. {
  114. //create ProcessCameraProvider instance
  115. val cameraProvider = cameraProviderFuture.get()
  116. //connect preview use case to the preview in the xml file
  117. val preview: PreviewView = requireView().findViewById(R.id.preview)
  118. val previewCase = Preview.Builder().build().also {
  119. it.setSurfaceProvider(preview.surfaceProvider)
  120. }
  121. //instantiate capture use case
  122. imageCapture = ImageCapture.Builder().build()
  123. try {
  124. //clear all bindings to previous use cases first
  125. cameraProvider.unbindAll()
  126. //bind lifecycle of camera to lifecycle of application
  127. cameraProvider.bindToLifecycle(
  128. requireActivity(),
  129. cameraSelector, previewCase
  130. )
  131. cameraProvider.bindToLifecycle(
  132. requireActivity(), cameraSelector,
  133. imageCapture
  134. )
  135. } catch (e: Exception) {
  136. Log.d(TAG, "Use case binding failed")
  137. }
  138. },
  139. //run asynchronous operation being listened to by cameraProviderFuture
  140. ContextCompat.getMainExecutor(requireActivity())
  141. )
  142. }
  143. //take photo
  144. private fun takePhoto() {
  145. imageCapture?.let {
  146. //create file with fileName using timestamped in milliseconds
  147. val file = File(
  148. requireActivity().externalMediaDirs[0],
  149. "snap_${System.currentTimeMillis()}"
  150. )
  151. //save image in above file
  152. val outputFileOptions =
  153. ImageCapture.OutputFileOptions.Builder(file).build()
  154. //call takePicture method with where to find image
  155. it.takePicture(
  156. outputFileOptions,
  157. imgCaptureExecutor,
  158. //set up callbacks for when picture is taken
  159. object : ImageCapture.OnImageSavedCallback {
  160. override fun onImageSaved(
  161. outputFileResults:
  162. ImageCapture.OutputFileResults
  163. ) {
  164. Log.i(TAG, "Image saved in ${file.toUri()}")
  165. }
  166. override fun onError(exception: ImageCaptureException) {
  167. Toast.makeText(
  168. requireActivity(),
  169. "Error taking photo",
  170. Toast.LENGTH_LONG
  171. ).show()
  172. Log.i(TAG, "Error taking photo: $exception")
  173. }
  174. }
  175. )
  176. }
  177. animateFlash()
  178. }
  179. //flash to provide feedback that photo taken
  180. private fun animateFlash() {
  181. val preview: PreviewView = requireView().findViewById(R.id.preview)
  182. preview.postDelayed({
  183. preview.foreground = ColorDrawable(Color.argb(125, 255, 255, 255))
  184. preview.postDelayed({
  185. preview.foreground = null
  186. }, 30)
  187. }, 60)
  188. }
  189. //display gallery
  190. private fun displayGallery() {
  191. val intent = Intent(requireActivity(), GalleryActivity::class.java)
  192. startActivity(intent)
  193. }
  194. }
展开查看全部
jljoyd4f

jljoyd4f2#

将所有“this,getApplicationContext”替换为getActivity()。在Java中
在Kotlin中,将所有“this,getApplicationContext”替换为活动
两种可能的定义:
片段中的getActivity()会传回目前与片段相关联的活动。(请参阅http://developer.android.com/reference/android/app/Fragment.html#getActivity())。getActivity()是使用者定义的。

相关问题