📅  最后修改于: 2023-12-03 14:59:16.829000             🧑  作者: Mango
Android-TextureView 是 Android 提供的一个 View,主要用于显示视频、Camera 预览等实时数据,相较于普通的 View,其有以下优势:
<TextureView
android:id="@+id/texture_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
TextureView textureView = new TextureView(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
relativeLayout.addView(textureView, layoutParams);
private TextureView mTextureView = findViewById(R.id.texture_view);
mTextureView.setSurfaceTextureListener(new SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
// surfaceTexture 可用,可以进行 Camera、MediaPlayer 等操作
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {
// TextureView 尺寸大小发生变化,可进行相应调整
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
// surfaceTexture 被销毁,释放相应资源
return false;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
// surfaceTexture 更新
}
});
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(mContext, mUri);
mMediaPlayer.setSurface(mTextureView.getSurface());
mTextureView.setOpaque(false);
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
Android-TextureView 提供了强大的视屏渲染能力,使得开发者可以更加方便地实现视频播放、相机预览等实时数据展示。在开发过程中需要注意设置好 SurfaceTextureListener 监听和 MediaPlayer 等播放器的配置,遵守相关的注意事项,才能更好地发挥其性能优势。