定位更改后视频视频视频消失

时间:2015-10-02 07:34:37

标签: android layout orientation android-videoview

我是Android的新手,我正在制作一个简单的应用程序,我将从本地设备获取视频并在我的布局中以视频视图播放。播放视频效果很好但是当我将方向从纵向更改为横向时,视频会消失。我相信我需要保存活动的状态。这是我的代码。

public class MainActivity extends AppCompatActivity {
private int position = 0;
private VideoView vidView;
private static int RESULT_LOAD_VIDEO = 1;
String vidDecodableString;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button buttonLoadVideo = (Button)findViewById(R.id.buttonLoadVideo);
    this.vidView = (VideoView)findViewById(R.id.myVideo);

    buttonLoadVideo.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_VIDEO);
        }
    });
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    try {
        if (requestCode == RESULT_LOAD_VIDEO && resultCode == RESULT_OK && null != data){
            Uri selectedVideo = data.getData();

            String[] filePathColumn = { MediaStore.Video.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            vidDecodableString = cursor.getString(columnIndex);

            //URI
            Uri vidUri = Uri.parse(vidDecodableString);
            vidView.setVideoURI(vidUri);

            MediaController vidControl = new MediaController(this);
            vidControl.setAnchorView(vidView);
            vidView.setMediaController(vidControl);
            vidView.start();

        } else {
            Toast.makeText(this, "Please select video to play.", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong.", Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putInt("Position", vidView.getCurrentPosition());
    vidView.pause();
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    position = savedInstanceState.getInt("Position");
    vidView.seekTo(position);
}

}

运行代码后,视频的选择和播放工作正常,但是当我更改方向时,视频加载消失。我在哪里做错了。请指教。

1 个答案:

答案 0 :(得分:0)

在清单

中添加此属性
<activity
            android:name=".YourActivity"
            android:configChanges="keyboardHidden|orientation|screenSize" />