Android用VideoView实现MP4作为页面背景

Demo: https://github.com/HunSem/BackgroundVideoTest

类似Tumblr, Spotify, Keep等应用在登录界面都有要采用了背景是动画的效果。自己现在做课程设计,也想使用,所以经过捣鼓以后实现如下图:

动态背景.gif
1. 新建一个用于显示VideoView背景mp4的布局文件 video_background.xml

背景mp4的布局文件 video_background.xml:


    
  

2. 在主内容布局中include上面的布局

承载背景布局的主内容布局需要定义为RelativeLayout布局,否则背景布局会挤占空间。
主内容布局文件:

    
  
     
  
      
    ....
   

3. 保留原布局的方法:

在主内容布局中申明一个RelativeLayout布局,include背景布局,然后,将原布局全部嵌套在该RelativeLayout布局中,并在原布局的最外一层设置属性
android:layout_centerInParent="true"

4. 在raw资源文件夹中放入需要播放的mp4文件
5. 在需要加载动态背景的Activity的OnCreate()方法中加入相关控制代码,实现自动循环播放

Activity中的OnCreate中加入代码:

myVideoView = (VideoView) findViewById(R.id.videoView);
final String videoPath = Uri.parse("android.resource://" + getPackageName() + "/" +R.raw.要播放的mp4文件).toString();
myVideoView.setVideoPath(videoPath);
myVideoView.start();
myVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {          
@Override 
  public void onPrepared(MediaPlayer mp) {        
    mp.start();        
    mp.setLooping(true);    
  }});
  myVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {   
@Override            
  public void onCompletion(MediaPlayer mp) {
    myVideoView.setVideoPath(videoPath);                
    myVideoView.start();            
  }        
});

你可能感兴趣的:(Android用VideoView实现MP4作为页面背景)