Search code examples
androidtextureview

How to load TextureView as a part of view


I would like to load TextureView as a part of my layout. I saw before some examples that it uses TextureView inside setContentView function.

    ...
    TextureView textureView = new TextureView(this);
    textureView.setSurfaceTextureListener(this);

    setContentView(textureView);

but I want to load this textureView as a part of a xml layout. how can I do?


Solution

  • Try this your can directly add TextureView in your layout like this

    <LinearLayout
        android:id="@+id/rootView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:orientation="vertical">
    
        <TextureView
            android:id="@+id/textureView1"
            android:layout_width="350dp"
            android:layout_height="350dp"
            android:layout_below="@+id/textView1" />
    </LinearLayout>
    

    or your can dynamically add TextureView in your layout like this

    public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
    
        LinearLayout rootLinearLayout;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            rootLinearLayout = findViewById(R.id.rootView);
            TextureView textureView = new TextureView(this);
            textureView.setSurfaceTextureListener(this);
            rootLinearLayout.addView(textureView);
    
    
        }
    
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
    
        }
    
        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {
    
        }
    
        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
            return false;
        }
    
        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
    
        }
    }