android 啟動頁面全屏播放視訊
有時候大家在啟動軟體的時候,會看到有一個比較炫酷的短視訊,覺得很有意思,現在做專案的時候也遇到了,跟大家分享一下。
首先,在 res 目錄下建一個資料夾 raw, 把你的視訊檔案(.mp4等)放進去。
然後, 在 layout 添加布局檔案 my_videoview.xml, 內容如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
接著, 在工程裡新增對應的java檔案,比如叫, videoview.java, 內容如下:
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class videoview extends Activity {
public static videoview inst = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
inst = this;
// 全屏顯示
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.my_videoview);
/*主要程式碼起始位置*/
final VideoView vv = (VideoView) this.findViewById(R.id.videoView);
final String uri = "android.resource://" + getPackageName() + "/" + R.raw.herologo;
vv.setVideoURI(Uri.parse(uri));
vv.start();
vv.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
mp.setLooping(false);
}
});
vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Intent intent = new Intent(inst, second.class);
startActivity(intent);
inst.finish();
}
});
/*主要程式碼結束位置*/
}
}
最後,需要在androidmanefest.xml 中宣告下類 videoview;
不過自己測試的時候,發現視訊在本人的手機上並沒有全屏顯示,而是在底部留下了不小的黑邊(可能視訊的尺寸與我的手機解析度不一樣)。於是搜尋,發現過載VideoView 的某些方法可以重新設定視訊播放器的大小。於是自定義類如下:
public class CustomVideoView extends VideoView{
public CustomVideoView(Context context) {
super(context);
}
public CustomVideoView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//我們重新計算高度(這樣就可以匹配不同手機的尺寸)
int width = getDefaultSize(0, widthMeasureSpec);
int height = getDefaultSize(0, heightMeasureSpec);
setMeasuredDimension(width, height);
}
}
然後,把佈局檔案 my_videoview.xml中的VideoView改成如下:
<xx.xx.xx.CustomVideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
把videoview 裡的 VideoView 類改成自定義的 CustomVideoView , 如下:
final CustomVideoView vv = (CustomVideoView ) this.findViewById(R.id.videoView);
重新編譯執行,視訊全屏播放,大功告成!!!