CameraFragment.kt 与 xml 相关的错误

Errors in connection of CameraFragment.kt with xml

我需要帮助,我在 fragment.kt 设置相机的过程中遇到错误

**

//fragmentcamera.xml

**

**<?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <androidx.camera.view.PreviewView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/preview"/>
    
        <Button
            android:id="@+id/btnTakePhoto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:text="Take photo"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@id/btnDisplayGallery"
            app:layout_constraintBottom_toBottomOf="parent"/>
    
        <Button
            android:id="@+id/btnDisplayGallery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="16dp"
            android:layout_marginBottom="300dp"
            android:text="Display gallery"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/btnTakePhoto" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>**

The following are images for camerafragment.kt

s

the errors that i am getting

将所有“this,getApplicationContext”替换为getActivity()。在Java

将所有“this,getApplicationContext”替换为activity。在 Kotlin 中。

两个可能的定义:

getActivity() 在 Fragment returns 中 Activity Fragment 当前关联。 (参见 http://developer.android.com/reference/android/app/Fragment.html#getActivity())。 getActivity() 是 user-defined.

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.google.common.util.concurrent.ListenableFuture
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


class cameraFragment : Fragment() {
    // TODO: Rename and change types of parameters
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
//ListenableFuture interface listens for async operations external to
// main thread
// requires type of activity being observed - ProcessCameraProvider
    private lateinit var cameraProviderFuture:
            ListenableFuture<ProcessCameraProvider>

    //used to decide whether to use front or back camera
    private lateinit var cameraSelector: CameraSelector

    //use case for capturing images
    private var imageCapture: ImageCapture? = null

    //interface that extends Executor to provide thread for capturing an image
    private lateinit var imgCaptureExecutor: ExecutorService

    //static variables
    companion object {
        //used for messages output in debugger
        val TAG = "cameraFragment"

        //used to check request code
        private var REQUEST_CODE = 101
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for requireActivity() fragment
        val view: View = inflater.inflate(
            R.layout.xml_camera,
            container,
            false
        )

        //get instance of ProcessCameraProvider
        cameraProviderFuture = ProcessCameraProvider.getInstance(requireActivity())

        //set default to back camera
        cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

        //instantiate imgCaptureExecutor
        imgCaptureExecutor = Executors.newSingleThreadExecutor()

        //check for permissions (similar to other sensors)
        if (ActivityCompat.checkSelfPermission(
                requireActivity(),
                Manifest.permission.CAMERA
            ) != PackageManager.PERMISSION_GRANTED
        )

        //request permissions
            ActivityCompat.requestPermissions(
                requireActivity(),
                arrayOf(
                    //array containing required permissions
                    Manifest.permission.CAMERA
                ),
                REQUEST_CODE
            )
        else {
            //if permission already granted, start camera
            startCamera()
        }
        //set up event listener for btnCapture click
        val btnTakePhoto: Button = view.findViewById(R.id.btnTakePhoto)
        btnTakePhoto.setOnClickListener {
            takePhoto()
        } //set up event listener for btnGallery click
        val btnDisplayGallery: Button = view.findViewById(R.id.btnDisplayGallery)
        btnDisplayGallery.setOnClickListener {
            displayGallery()
        }
        return view
    }

    //invoked when permissions change
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        //check that request code matches and permission granted
        if (requestCode == REQUEST_CODE &&
            grantResults.isNotEmpty() &&
            grantResults[0] == PackageManager.PERMISSION_GRANTED
        ) {
            //if permission now granted, start camera
            startCamera()
        }
    }

    //listen for data from camera
    private fun startCamera() {
        cameraProviderFuture.addListener(
            {
                //create ProcessCameraProvider instance
                val cameraProvider = cameraProviderFuture.get()
                //connect preview use case to the preview in the xml file
                val preview: PreviewView = requireView().findViewById(R.id.preview)
                val previewCase = Preview.Builder().build().also {
                    it.setSurfaceProvider(preview.surfaceProvider)
                }
                //instantiate capture use case
                imageCapture = ImageCapture.Builder().build()

                try {
                    //clear all bindings to previous use cases first
                    cameraProvider.unbindAll()
                    //bind lifecycle of camera to lifecycle of application
                    cameraProvider.bindToLifecycle(
                        requireActivity(),
                        cameraSelector, previewCase
                    )
                    cameraProvider.bindToLifecycle(
                        requireActivity(), cameraSelector,

                        imageCapture
                    )
                } catch (e: Exception) {
                    Log.d(TAG, "Use case binding failed")
                }
            },
//run asynchronous operation being listened to by cameraProviderFuture
            ContextCompat.getMainExecutor(requireActivity())
        )
    }

    //take photo
    private fun takePhoto() {
        imageCapture?.let {
            //create file with fileName using timestamped in milliseconds
            val file = File(
                requireActivity().externalMediaDirs[0],
                "snap_${System.currentTimeMillis()}"
            )
            //save image in above file
            val outputFileOptions =
                ImageCapture.OutputFileOptions.Builder(file).build()

            //call takePicture method with where to find image
            it.takePicture(
                outputFileOptions,
                imgCaptureExecutor,
                //set up callbacks for when picture is taken
                object : ImageCapture.OnImageSavedCallback {
                    override fun onImageSaved(
                        outputFileResults:
                        ImageCapture.OutputFileResults
                    ) {
                        Log.i(TAG, "Image saved in ${file.toUri()}")
                    }

                    override fun onError(exception: ImageCaptureException) {
                        Toast.makeText(
                            requireActivity(),
                            "Error taking photo",
                            Toast.LENGTH_LONG
                        ).show()
                        Log.i(TAG, "Error taking photo: $exception")
                    }
                }
            )
        }
        animateFlash()
    }

    //flash to provide feedback that photo taken

    private fun animateFlash() {
        val preview: PreviewView = requireView().findViewById(R.id.preview)
        preview.postDelayed({
            preview.foreground = ColorDrawable(Color.argb(125, 255, 255, 255))
            preview.postDelayed({
                preview.foreground = null
            }, 30)

        }, 60)

    }

    //display gallery
    private fun displayGallery() {
        val intent = Intent(requireActivity(), GalleryActivity::class.java)
        startActivity(intent)
    }
}