How to Create Custom Camera using CameraX in Android?
CameraX is used to create a custom camera in the app. CameraX is a Jetpack support library, built to help you make camera app development easier. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Step by Step Implementation
Step 1: Create a new project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add dependency to the build.gradle file and click “sync now”
def camerax_version = “1.0.0-beta07”
// CameraX core library using camera2 implementation
// CameraX Lifecycle Library
// CameraX View class
If kotlin extension is missing, add kotlin-android-extensions as shown below and click on “Sync now”.
Step 3: Add Camera permission
Go to AndroidManifest.xml and add the camera permission.
<uses-feature android:name=”android.hardware.camera.any” />
<uses-permission android:name=”android.permission.CAMERA” />
Step 4: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. Notice that there is a view called PreviewView with id viewFinder which we will use as Viewfinder for the camera.
Step 5: Create capture button drawable
Go to res > drawable and create a new file capture_button.xml. Below is the code of it.
Step 6: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.