Android TextureView Using Kotlin With Example

In this article, we will learn about android TextureView using Kotlin. We will go through various example that demonstrates how to use different attributes of TextureView. For example,

In this article, we will get answer to questions like –

  • What is TextureView?
  • Why should we consider TextureView while designing ui for any app?
  • What are possibilities using TextureView while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing TextureView Output of textureview using kotlin tutorial with example

TextureView Output

Getting Started

We can define android TextureView widget as below –

A TextureView is subclass of View Class that can be used to display content stream such as video or or OpenGL scene. Content steam can come from application’s process or remove process.

Note – TextureView can only be used in hardware accelerated window.

How to use TextureView

All you have to do is get it’s surfaceTexture. Then, surfaceTexture can be used to render the content. You can use getSurfaceTexture() or TextureView.SurfaceTextureListener to get the surfaceTexture.

Please note that surfaceTexture is available only after textureView is attached to window. So, it is advisable to use listener to be notified when surfaceTexture is available.

Also, only one producer can use textureView. So, you are using textureView for camera preview, you can not use lockCanvas() to draw onto textureView at same time.

Now, how do we use TextureView 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 TextureView. 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 TextureView 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 TextureView in Kotlin

Follow steps below to use TextureView in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">TextureView</string>
        <string name="permission_required">Camera permission required to run application.</string>
    </resources>
    
  • 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:gravity="center">
    
        <TextView
            android:id="@+id/info"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"/>
    
    </FrameLayout>
    

    Here, we have modified the layout in activity_main.xml file. We have added textView that will be used to display message if necessary.

  • Setup For Camera Permission At Runtime.

    We need to add camera permission for this app because you must have access to camera of the device for this application to work.

    So, add below code in AndroidManifest.xml to get permission to access camera by the user.

    <uses-permission android:name="android.permission.CAMERA"/>
    

    Also, We need to write code to get permission at runtime (for device having android version >= Marshmallow).

    So, open src/main/java/com.tutorialwing.textureview/MainActivity.kt file. Then, add below code into it.

    package com.tutorialwing.textureview
    
    import android.app.AlertDialog
    import android.content.DialogInterface
    import android.content.pm.PackageManager
    import android.graphics.SurfaceTexture
    import android.hardware.Camera
    import android.os.Build
    import android.os.Bundle
    import android.support.v4.app.ActivityCompat
    import android.support.v4.content.ContextCompat
    import android.support.v7.app.AppCompatActivity
    import android.view.Gravity
    import android.view.TextureView
    import android.widget.FrameLayout
    import android.widget.TextView
    
    import java.io.IOException
    
    import android.Manifest.permission.CAMERA
    
    class MainActivity : AppCompatActivity(), TextureView.SurfaceTextureListener {
    
        private var mTextureView: TextureView? = null
        private var mCamera: Camera? = null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            val result = checkPermission()
            if (result) {
                // perform something if permission is granted.
            }
        }
    
        private fun checkPermission(): Boolean {
            val currentAPIVersion = Build.VERSION.SDK_INT
            if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
                if (ContextCompat.checkSelfPermission(this, CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, CAMERA)) {
                        showPermissionAlert()
                    } else {
                        ActivityCompat.requestPermissions(this@MainActivity, arrayOf(CAMERA), CAMERA_REQUEST_CODE)
                    }
                    return false
                } else {
                    return true
                }
            } else {
                return true
            }
        }
    
        private fun showPermissionAlert() {
            val alertBuilder = AlertDialog.Builder(this)
            alertBuilder.setCancelable(true)
            alertBuilder.setTitle("Permission Required")
            alertBuilder.setMessage("Permission to access camera is needed to run this application")
            alertBuilder.setPositiveButton(android.R.string.yes) { dialog, which -> ActivityCompat.requestPermissions(this@MainActivity, arrayOf(CAMERA), CAMERA_REQUEST_CODE) }
            val alert = alertBuilder.create()
            alert.show()
        }
    
        override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
            when (requestCode) {
                CAMERA_REQUEST_CODE -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Write code to setup textureView if permission is granted by user.
                } else if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
                    // // Write code to perform other task if permission is not granted by user.
                }
            }
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    
        companion object {
    
            val CAMERA_REQUEST_CODE = 100
        }
    }
    

    As we can see, we have written code to get camera permission at runtime. We will setup textureView only if permission is granted. Otherwise, we will show some message to the user.

  • Create TextureView Widget in Kotlin file

    Now, we will write code to show textureView if permission is granted. We will also set a listener that is needed to perform some action when surfaceTexture is available. We can do these as below –

    TextureView mTextureView = TextureView(this)
    mTextureView!!.surfaceTextureListener = this
    setContentView(mTextureView)
    

    Also, implement the listener as below –

    
    class MainActivity : AppCompatActivity(), TextureView.SurfaceTextureListener {
    
        // Some other code..
        // ...
    
        override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, i: Int, i1: Int) {
            // Perform action when surfaceTexture is available. For example, start camera etc. 
        }
    
        override fun onSurfaceTextureSizeChanged(surfaceTexture: SurfaceTexture, i: Int, i1: Int) {
            // Ignored, Camera does all the work for us
        }
    
        override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean {
            // Perform action when surfaceTexture is destroyed. For example, stop camera, release resources etc.
            return true
        }
    
        override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {
            // Invoked every time there's a new Camera preview frame.
        }
    
  • Finally, our MainActivity.kt will look like below –

    package com.tutorialwing.textureview
    
    import android.Manifest.permission.CAMERA
    import android.content.pm.PackageManager
    import android.graphics.SurfaceTexture
    import android.hardware.Camera
    import android.os.Build
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.view.Gravity
    import android.view.TextureView
    import android.widget.FrameLayout
    import androidx.appcompat.app.AlertDialog
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    import com.tutorialwing.textureview.databinding.ActivityMainBinding
    import java.io.IOException
    
    class MainActivity : AppCompatActivity(), TextureView.SurfaceTextureListener {
    
    	private lateinit var binding: ActivityMainBinding
    
    	private var mTextureView: TextureView? = null
    	private var mCamera: Camera? = null
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		val result = checkPermission()
    		if (result) {
    			setupTextureView()
    		}
    	}
    
    	private fun setupTextureView() {
    		mTextureView = TextureView(this)
    		mTextureView!!.surfaceTextureListener = this
    		setContentView(mTextureView)
    	}
    
    	private fun setMessageView() {
    		setContentView(R.layout.activity_main)
    		binding.info.setText(R.string.permission_required)
    	}
    
    	private fun checkPermission(): Boolean {
    		val currentAPIVersion = Build.VERSION.SDK_INT
    		return if (currentAPIVersion >= Build.VERSION_CODES.M) {
    			if (ContextCompat.checkSelfPermission(
    					this,
    					CAMERA
    				) != PackageManager.PERMISSION_GRANTED
    			) {
    				if (ActivityCompat.shouldShowRequestPermissionRationale(this, CAMERA)) {
    					showPermissionAlert()
    				} else {
    					ActivityCompat.requestPermissions(
    						this@MainActivity,
    						arrayOf(CAMERA),
    						CAMERA_REQUEST_CODE
    					)
    				}
    				false
    			} else {
    				true
    			}
    		} else {
    			true
    		}
    	}
    
    	private fun showPermissionAlert() {
    		val alertBuilder = AlertDialog.Builder(this)
    		alertBuilder.setCancelable(true)
    		alertBuilder.setTitle("Permission Required")
    		alertBuilder.setMessage("Permission to access camera is needed to run this application")
    		alertBuilder.setPositiveButton(android.R.string.yes) { dialog, which ->
    			ActivityCompat.requestPermissions(
    				this@MainActivity,
    				arrayOf(CAMERA),
    				CAMERA_REQUEST_CODE
    			)
    		}
    		val alert = alertBuilder.create()
    		alert.show()
    	}
    
    	override fun onRequestPermissionsResult(
    		requestCode: Int,
    		permissions: Array<String>,
    		grantResults: IntArray
    	) {
    		when (requestCode) {
    			CAMERA_REQUEST_CODE -> if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    				setupTextureView()
    			} else if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_DENIED) {
    				setMessageView()
    			}
    		}
    		super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    	}
    
    	override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture, p1: Int, p2: Int) {
    		mCamera = Camera.open()
    
    		val previewSize = mCamera!!.parameters.previewSize
    		mTextureView!!.layoutParams =
    			FrameLayout.LayoutParams(previewSize.width, previewSize.height, Gravity.CENTER)
    
    		try {
    			mCamera!!.setPreviewTexture(surfaceTexture)
    			mCamera!!.startPreview()
    		} catch (ioe: IOException) {
    			// Something bad happened
    		}
    
    		mTextureView!!.alpha = 1.0f;
    		mTextureView!!.rotation = 90.0f;
    	}
    
    	override fun onSurfaceTextureSizeChanged(p0: SurfaceTexture, p1: Int, p2: Int) {
    		// Ignored, Camera does all the work for us
    	}
    
    	override fun onSurfaceTextureDestroyed(p0: SurfaceTexture): Boolean {
    		mCamera!!.stopPreview()
    		mCamera!!.release()
    		return true
    	}
    
    	override fun onSurfaceTextureUpdated(p0: SurfaceTexture) {
    		// Invoked every time there's a new Camera preview frame.
    	}
    
    	companion object {
    		val CAMERA_REQUEST_CODE = 100
    	}
    }
    

    Here, we are showing how to use textureView using kotlin in android application. As you can see, how we are getting the permission at runtime. Then, we are setting up textureView and showing the camera when surfaceTexture is available. Also, releasing the resources when surfaceTexture is destroyed.

Now, run the application. We will get output as below –

Tutorialwing TextureView Output of textureview using kotlin tutorial with example

TextureView Output

Different Attributes of TextureView in XML

Now, we will see how to use different attributes of Android TextureView using Kotlin to customise it –

Set Id of TextureView

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 TextureView using android:id attribute like below –

    <TextureView
        android:id="@+id/textureView_ID"
        />

Here, we have set id of TextureView as textureView_ID using android:id=”” attribute. So, if we need to reference this TextureView, we need to use this id – textureView_ID.
Learn to Set ID of TextureView Dynamically

Set Width of TextureView

We use android:layout_width=”” attribute to set width of TextureView.
We can do it as below –

    <TextureView
        android:id="@+id/textureView_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of TextureView Dynamically

Set Height of TextureView

We use android:layout_height=”” attribute to set height of TextureView.
We can do it as below –

    <TextureView
        android:id="@+id/textureView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of TextureView Dynamically

Set Padding of TextureView

We use android:padding=”” attribute to set padding of TextureView.
We can do it as below –

    <TextureView
        android:id="@+id/textureView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in TextureView using android:padding=”” attribute.
Learn to Set Padding of TextureView Dynamically

Set Margin of TextureView

We use android:layout_margin=”” attribute to set margin of TextureView.
We can do it as below –

    <TextureView
        android:id="@+id/textureView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in TextureView using android:layout_margin=”” attribute.
Learn to Set Margin of TextureView Dynamically

Set Background of TextureView

We use android:background=”” attribute to set background of TextureView.
We can do it as below –

    <TextureView
        android:id="@+id/textureView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in TextureView using android:background=”” attribute.
Learn to Set Background of TextureView Dynamically

Set Visibility of TextureView

We use android:visibility=”” attribute to set visibility of TextureView.
We can do it as below –

    <TextureView
        android:id="@+id/textureView_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of TextureView using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of TextureView Dynamically

Till now, we have see how to use android TextureView using Kotlin. We have also gone through different attributes of TextureView to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android TextureView Widget

Below are the various attributes that are used to customise android TextureView Widget. However, you can check the complete list of attributes of TextureView 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 TextureView are –

Sr. XML Attributes Description
1 android:background Sets background of the view.
2 android:backgroundTintMode Sets blending mode used to apply the background tint.
3 android:clickable Sets whether view is clickable or not
4 android:elevation Sets z-depth of the view
5 android:id Sets id of the view
6 android:padding Sets padding of the view

We have seen different attributes of TextureView and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is TextureView, how can we use android TextureView using Kotlin ? etc. We also went through different attributes of android TextureView.

Leave a Reply