In this article, we will learn about android SurfaceView using Kotlin. We will go through various example that demonstrates how to use different attributes of SurfaceView. For example,
In this article, we will get answer to questions like –
- What is SurfaceView?
- Why should we consider SurfaceView while designing ui for any app?
- What are possibilities using SurfaceView while designing ui? etc.
Let’s have a quick demo of things we want to cover in this tutorial –
Output
Getting Started
We can define android SurfaceView widget as below –
SurfaceView is subclass of View class that are provides a drawing surface embedded inside of View hierarchy.
Now, how do we use SurfaceView in android application ?
Creating New Project
At first, we will create an application.
So, follow steps below to create any android project in Kotlin –
Step | Description |
---|---|
1. | Open Android Studio (Ignore if already done). |
2. | Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next. |
3. | In next screen, select project name as SurfaceView. Then, fill other required details. |
4. | Then, clicking on Finish button creates new project. |
Newbie in Android ?
Some very important concepts (Recommended to learn before you move ahead)
Before we move ahead, we need to setup for viewBinding to access Android SurfaceView Using Kotlin file without using findViewById() method.
Setup ViewBinding
Add viewBinding true in app/build.gradle file.
android { // OTHER CODE... buildFeatures { viewBinding true } }
Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.
class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) } }
Now, we can access view in Kotlin file without using findViewById() method.
Using SurfaceView in Kotlin
Follow steps below to use SurfaceView in newly created project –
- Open res/values/strings.xml file. Then, add below code into it.
<resources> <string name="app_name">SurfaceView</string> <string name="take_photo">TAKE PHOTO</string> <string name="permission_required">Permission Required</string> <string name="permission_message">You must grant permission to access camera and external storage to run this application.</string> <string name="permission_warning">All permissions are required.</string> <string name="yes">Yes</string> </resources>
-
Then, open res/values/dimens.xml file. Now, add below code into it.
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="show_permission_padding">20dp</dimen> </resources>
Note: If there is no dimens.xml file, create a new file, dimens.xml, in res/values folder.
- Open res/layout/activity_main.xml file. Then, add below code in it –
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <SurfaceView android:id="@+id/surfaceView" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" /> <Button android:id="@+id/startBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal|bottom" android:text="@string/take_photo" android:visibility="gone" /> <TextView android:id="@+id/showPermissionMsg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:padding="@dimen/show_permission_padding" android:text="@string/permission_message" android:textAlignment="center" android:textStyle="bold|italic" android:visibility="gone" /> </FrameLayout>
Here, we have defined ui to show surfaceView and a button. When all the permissions are granted by user, we show camera to the user. If not, we show a message accordingly.
-
Setup For Required Permission at runtime.
Now, we will add code to take CAMERA and WRITE_EXTERNAL_STORAGE permissions from user. As we already know, App should provide runtime permissions for devices on or after android 6.0 . So, we will also add code to get permissions at runtime.
Permission prior to Android 6.0
Open main/AndroidManifest.xml file. Then, add below code into it.
<uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
For devices prior to android 6.0, we write all the required permissions in AndroidManifest file. So, we have written all the permissions in this file.
Permission after Android 6.0
We will write code in kotlin file to get permissions at runtime. So, open main/java/com.tutorialwing.surfaceview/MainActivity.kt file. Then, write below code into it.
package com.tutorialwing.surfaceview import android.Manifest.permission.CAMERA import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.app.AlertDialog import android.content.pm.PackageManager import android.hardware.Camera import android.os.Build import android.os.Bundle import android.os.Environment import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.Toast import java.util.* class MainActivity : AppCompatActivity(), SurfaceHolder.Callback, Camera.PictureCallback { private val neededPermissions = arrayOf(CAMERA, WRITE_EXTERNAL_STORAGE) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Check code to get permissions if needed. val result = checkPermission() if (result) { // if permissions granted, update ui accordingly. } } private fun checkPermission(): Boolean { val currentAPIVersion = Build.VERSION.SDK_INT if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) { val permissionsNotGranted = ArrayList<String>() for (permission in neededPermissions) { if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { permissionsNotGranted.add(permission) } } if (permissionsNotGranted.size > 0) { var shouldShowAlert = false for (permission in permissionsNotGranted) { shouldShowAlert = ActivityCompat.shouldShowRequestPermissionRationale(this, permission) } val arr = arrayOfNulls<String>(permissionsNotGranted.size) val permissions = permissionsNotGranted.toArray(arr) if (shouldShowAlert) { showPermissionAlert(permissions) } else { requestPermissions(permissions) } return false } } return true } private fun showPermissionAlert(permissions: Array<String?>) { val alertBuilder = AlertDialog.Builder(this) alertBuilder.setCancelable(true) alertBuilder.setTitle(R.string.permission_required) alertBuilder.setMessage(R.string.permission_message) alertBuilder.setPositiveButton(android.R.string.yes) { _, _ -> requestPermissions(permissions) } val alert = alertBuilder.create() alert.show() } private fun requestPermissions(permissions: Array<String?>) { ActivityCompat.requestPermissions(this@MainActivity, permissions, REQUEST_CODE) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { REQUEST_CODE -> { for (result in grantResults) { if (result == PackageManager.PERMISSION_DENIED) { // Not all permissions granted. Show some message and return. return } } // All permissions are granted. Do the work accordingly. } } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } companion object { const val REQUEST_CODE = 100 } }
Above code have been written to get permissions at runtime. We need CAMERA and WRITE_EXTERNAL_STORAGE permissions to run the application.
Different methods are –
- (a) checkPermission() – This method checks if all the required permissions have been granted or not. If not, either showPermissionAlert() or requestPermissions() method is called.
- (b) showPermissionAlert() – This method display alert dialog to the user that contains message (informing user that all the permissions must be granted to the user to run the application).
- (c) requestPermissions() – This method calls ActivityCompat.requestPermissions method that display ui to grant all the permissions by user.
- (d) onRequestPermissionsResult() – This method is called when action on all permissions are complete. Permissions may be granted or rejected.
-
Setup SurfaceView and Show Camera in kotlin file
Till now, we have done basic setup for surfaceView using kotlin. Now, we will show surfaceView and show camera to the user. Then, user can take appropriate action like taking photo etc.
We assume that all the permissions have been granted by user.
So, open src/main/java/com.tutorialwing.surfaceview/MainActivity.kt file. Then, add below code into it.
package com.tutorialwing.surfaceview import android.Manifest.permission.CAMERA import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.content.pm.PackageManager import android.hardware.Camera import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Environment import android.view.SurfaceHolder import android.view.SurfaceView import android.view.TextureView import android.view.View import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.tutorialwing.surfaceview.databinding.ActivityMainBinding import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException class MainActivity : AppCompatActivity(), SurfaceHolder.Callback, Camera.PictureCallback { private lateinit var binding: ActivityMainBinding private var surfaceHolder: SurfaceHolder? = null private var camera: Camera? = null private val neededPermissions = arrayOf(CAMERA, WRITE_EXTERNAL_STORAGE) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val result = checkPermission() if (result) { setupSurfaceHolder() } } // Other code related to camera permissions. private fun setupSurfaceHolder() { binding.startBtn.visibility = View.VISIBLE binding.surfaceView.visibility = View.VISIBLE surfaceHolder = binding.surfaceView.holder binding.surfaceView.holder.addCallback(this) setBtnClick() } private fun setBtnClick() { binding.startBtn.setOnClickListener { captureImage() } } private fun captureImage() { if (camera != null) { camera!!.takePicture(null, null, this) } } override fun surfaceCreated(surfaceHolder: SurfaceHolder) { startCamera() } private fun startCamera() { camera = Camera.open() camera!!.setDisplayOrientation(90) try { camera!!.setPreviewDisplay(surfaceHolder) camera!!.startPreview() } catch (e: IOException) { e.printStackTrace() } } override fun surfaceChanged(surfaceHolder: SurfaceHolder, i: Int, i1: Int, i2: Int) { resetCamera() } private fun resetCamera() { if (surfaceHolder!!.surface == null) { // Return if preview surface does not exist return } // Stop if preview surface is already running. camera!!.stopPreview() try { // Set preview display camera!!.setPreviewDisplay(surfaceHolder) } catch (e: IOException) { e.printStackTrace() } // Start the camera preview... camera!!.startPreview() } override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) { releaseCamera() } private fun releaseCamera() { camera!!.stopPreview() camera!!.release() camera = null } override fun onPictureTaken(bytes: ByteArray, camera: Camera) { saveImage(bytes) resetCamera() } private fun saveImage(bytes: ByteArray) { val outStream: FileOutputStream try { val fileName = "TUTORIALWING_" + System.currentTimeMillis() + ".jpg" val file = File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName ) outStream = FileOutputStream(file) outStream.write(bytes) outStream.close() Toast.makeText(this@MainActivity, "Picture Saved: $fileName", Toast.LENGTH_LONG).show() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } }
Above code are responsible for setup of surfaceView using kotlin. We have shown when to show surfaceView or camera, how to take picture using camera, how to save picture taken using camera etc. Basically, we are showing how can you manage your surfaceView using Kotlin to display camera successfully.
Here, we have implemented two interface –
-
SurfaceHolder.Callback
SurfaceHolder.Callback interface is used to receive changes about the surface and setup surfaceView accordingly. Below methods are implemented using this interface –
- (i) surfaceCreated() method – This method is called immediately after surface is first created. So, here we are starting the camera in this application.
- (ii) surfaceChanged() method – This method is called when there is any structural changes to the surface. As you would have guessed by now, we reset the camera when-ever there is any changes to the surface. Then, start the camera again.
- (iii) surfaceDestroyed() method – This method is called immediately before surface is being destroyed. Since surface is being destroyed, we release all the resources here. For example, access to camera etc.
-
Camera.PictureCallback
This is called when picture is taken by camera. There is one method – onPictureTaken which is called when picture is taken. So, we have written code to save taken picture in external storage. Finally, we are showing a toast message to the user about saved picture.
-
-
Final code in main/java/com.tutorialwing.surfaceview/MainActivity.kt file including permissions at runtime and surfaceView setup etc. would be like below –
package com.tutorialwing.surfaceview import android.Manifest.permission.CAMERA import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.content.pm.PackageManager import android.hardware.Camera import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Environment import android.view.SurfaceHolder import android.view.SurfaceView import android.view.TextureView import android.view.View import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import com.tutorialwing.surfaceview.databinding.ActivityMainBinding import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException class MainActivity : AppCompatActivity(), SurfaceHolder.Callback, Camera.PictureCallback { private lateinit var binding: ActivityMainBinding private var surfaceHolder: SurfaceHolder? = null private var camera: Camera? = null private val neededPermissions = arrayOf(CAMERA, WRITE_EXTERNAL_STORAGE) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val result = checkPermission() if (result) { setupSurfaceHolder() } } private fun checkPermission(): Boolean { val currentAPIVersion = Build.VERSION.SDK_INT if (currentAPIVersion >= Build.VERSION_CODES.M) { val permissionsNotGranted = ArrayList<String>() for (permission in neededPermissions) { if (ContextCompat.checkSelfPermission( this, permission ) != PackageManager.PERMISSION_GRANTED ) { permissionsNotGranted.add(permission) } } if (permissionsNotGranted.size > 0) { var shouldShowAlert = false for (permission in permissionsNotGranted) { shouldShowAlert = ActivityCompat.shouldShowRequestPermissionRationale(this, permission) } val arr = arrayOfNulls<String>(permissionsNotGranted.size) val permissions = permissionsNotGranted.toArray(arr) if (shouldShowAlert) { showPermissionAlert(permissions) } else { requestPermissions(permissions) } return false } } return true } private fun showPermissionAlert(permissions: Array<String?>) { val alertBuilder = AlertDialog.Builder(this) alertBuilder.setCancelable(true) alertBuilder.setTitle(R.string.permission_required) alertBuilder.setMessage(R.string.permission_message) alertBuilder.setPositiveButton(R.string.yes) { _, _ -> requestPermissions(permissions) } val alert = alertBuilder.create() alert.show() } private fun requestPermissions(permissions: Array<String?>) { ActivityCompat.requestPermissions(this@MainActivity, permissions, REQUEST_CODE) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { when (requestCode) { REQUEST_CODE -> { for (result in grantResults) { if (result == PackageManager.PERMISSION_DENIED) { Toast.makeText( this@MainActivity, R.string.permission_warning, Toast.LENGTH_LONG ).show() binding.showPermissionMsg.visibility = View.VISIBLE return } } setupSurfaceHolder() } } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } private fun setupSurfaceHolder() { binding.startBtn.visibility = View.VISIBLE binding.surfaceView.visibility = View.VISIBLE surfaceHolder = binding.surfaceView.holder binding.surfaceView.holder.addCallback(this) setBtnClick() } private fun setBtnClick() { binding.startBtn.setOnClickListener { captureImage() } } private fun captureImage() { if (camera != null) { camera!!.takePicture(null, null, this) } } override fun surfaceCreated(surfaceHolder: SurfaceHolder) { startCamera() } private fun startCamera() { camera = Camera.open() camera!!.setDisplayOrientation(90) try { camera!!.setPreviewDisplay(surfaceHolder) camera!!.startPreview() } catch (e: IOException) { e.printStackTrace() } } override fun surfaceChanged(surfaceHolder: SurfaceHolder, i: Int, i1: Int, i2: Int) { resetCamera() } private fun resetCamera() { if (surfaceHolder!!.surface == null) { // Return if preview surface does not exist return } // Stop if preview surface is already running. camera!!.stopPreview() try { // Set preview display camera!!.setPreviewDisplay(surfaceHolder) } catch (e: IOException) { e.printStackTrace() } // Start the camera preview... camera!!.startPreview() } override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) { releaseCamera() } private fun releaseCamera() { camera!!.stopPreview() camera!!.release() camera = null } override fun onPictureTaken(bytes: ByteArray, camera: Camera) { saveImage(bytes) resetCamera() } private fun saveImage(bytes: ByteArray) { val outStream: FileOutputStream try { val fileName = "TUTORIALWING_" + System.currentTimeMillis() + ".jpg" val file = File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName ) outStream = FileOutputStream(file) outStream.write(bytes) outStream.close() Toast.makeText(this@MainActivity, "Picture Saved: $fileName", Toast.LENGTH_LONG).show() } catch (e: FileNotFoundException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } } companion object { const val REQUEST_CODE = 100 } }
Final code in MainActivity.kt file would be as shown above that includes camera permissions at runtime, setup for surfaceView using kotlin, camera setup, save taken picture into external folder etc.
Note – You can compare this with your changes in MainActivity.kt file. If you get any problem, you can directly copy/paste this code and check if the app is working as expected.
-
Since AndroidManifest.xml file is very important in any android application, we are also going to see the content inside this file.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tutorialwing.surfaceview"> <uses-permission android:name="android.permission.CAMERA"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.SurfaceView"> <activity android:name=".MainActivity" android:exported="true"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Now, run the application. We will get output as below –
Different Attributes of SurfaceView in XML
Now, we will see how to use different attributes of Android SurfaceView using Kotlin to customise it –
Set Id of SurfaceView
Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of SurfaceView using android:id attribute like below –
<SurfaceView android:id="@+id/surfaceView_ID" />
Here, we have set id of SurfaceView as surfaceView_ID using android:id=”” attribute. So, if we need to reference this SurfaceView, we need to use this id – surfaceView_ID.
Set Width of SurfaceView
We use android:layout_width=”” attribute to set width of SurfaceView.
We can do it as below –
<SurfaceView android:id="@+id/surfaceView_ID" android:layout_width="wrap_content" />
Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Set Height of SurfaceView
We use android:layout_height=”” attribute to set height of SurfaceView.
We can do it as below –
<SurfaceView android:id="@+id/surfaceView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" />
Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Set Padding of SurfaceView
We use android:padding=”” attribute to set padding of SurfaceView.
We can do it as below –
<SurfaceView android:id="@+id/surfaceView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" />
Here, we have set padding of 10dp in SurfaceView using android:padding=”” attribute.
Set Margin of SurfaceView
We use android:layout_margin=”” attribute to set margin of SurfaceView.
We can do it as below –
<SurfaceView android:id="@+id/surfaceView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" />
Here, we have set margin of 10dp in SurfaceView using android:layout_margin=”” attribute.
Set Background of SurfaceView
We use android:background=”” attribute to set background of SurfaceView.
We can do it as below –
<SurfaceView android:id="@+id/surfaceView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ff0000" />
Here, we have set background of color #ff0000 in SurfaceView using android:background=”” attribute.
Set Visibility of SurfaceView
We use android:visibility=”” attribute to set visibility of SurfaceView.
We can do it as below –
<SurfaceView android:id="@+id/surfaceView_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" />
Here, we have set visibility of SurfaceView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Till now, we have see how to use android SurfaceView using Kotlin. We have also gone through different attributes of SurfaceView to perform certain task. Let’s have a look at list of such attributes and it’s related task.
Different Attributes of Android SurfaceView Widget
Below are the various attributes that are used to customise android SurfaceView Widget. However, you can check the complete list of attributes of SurfaceView in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –
Some of the popular attributes of android surfaceView inherited from View class are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:background | Defines background of the view. |
2 | android:theme | Defines a theme of the view |
3 | android:visibility | Defines visibility (VISIBLE, INVISIBLE or GONE) of the view |
4 | android:elevation | Defines z-depth of the view |
5 | android:id | Sets id of the view |
6 | android:padding | Defines padding of the view |
We have seen different attributes of SurfaceView and how to use it. If you wish to visit post to learn more about it
Thus, we have seen what is SurfaceView, how can we use android SurfaceView using Kotlin ? etc. We also went through different attributes of android SurfaceView.
You must be logged in to post a comment.