2015-10-02 116 views
0

我是新來的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); 
} 

}

後,我運行的代碼,選擇和播放視頻作品,但是當我改變方向,視頻加載消失。我在哪裏做錯了。請指教。

回答

0

清單中

<activity 
      android:name=".YourActivity" 
      android:configChanges="keyboardHidden|orientation|screenSize" /> 
+0

添加此屬性,它的工作!我忘了這件事。哈哈哈。我太傻了。我仍然需要記住這麼多事情。哈哈哈。謝謝您的幫助。 –

+0

=)兄弟沒問題 –