如何将 android 资源路径转换为字符串

How to convert android resource path to string

这是我的视频视图 class 并且效果很好

private void CopyReadVdo() {
    setContentView(R.layout.video_player);
    VideoView view = (VideoView) findViewById(R.id.videoview);
    String path = "android.resource://" + getPackageName() + "/" + R.raw.video1;
    Uri uri = Uri.parse(path);
    view.setVideoURI(uri);
    MediaController mediaController = new MediaController(this);
    mediaController.setAnchorView(view);
    view.setMediaController(mediaController);
    view.start();
}

我需要使用像

这样的参数来调用这个函数
private void CopyReadVdo(String vdoname) {
    setContentView(R.layout.video_player);

    VideoView view = (VideoView) findViewById(R.id.videoview);
    String path = "android.resource://" + getPackageName() + "/" + vdoname;
    Uri uri = Uri.parse(path);
    view.setVideoURI(uri);
    MediaController mediaController = new MediaController(this);
    mediaController.setAnchorView(view);
    view.setMediaController(mediaController);
    view.start();
}

但是显示错误无法播放此视频。提前致谢。

试试下面的代码

Uri video = Uri.parse("android.resource://com.example.sample/raw/filename");

首先尝试从资源名称 vdoname

获取资源 ID rawId
int rawId = getResources().getIdentifier(vdoname,  "raw", getPackageName());
String path = "android.resource://" + getPackageName() + "/" + rawId;

更新:shaktee 作为 vdoname 传递给 CopyReadVdo 函数而不是 R.raw.shaktee

或者将 vdoname 的类型更改为 int 并将 R.raw.shaktee 传递给 CopyReadVdo 函数

private void CopyReadVdo(int vdoname) {
    setContentView(R.layout.video_player);

    VideoView view = (VideoView) findViewById(R.id.videoview);
    String path = "android.resource://" + getPackageName() + "/" + vdoname;
    Uri uri = Uri.parse(path);
    view.setVideoURI(uri);
    MediaController mediaController = new MediaController(this);
    mediaController.setAnchorView(view);
    view.setMediaController(mediaController);
    view.start();
}