简体   繁体   中英

How to loop a VideoView element in MainActivity.java?

I've written an application which plays a video until you tap the screen and it exits. A basic screensaver essentially. The app will launch and play the video however it stops on the last frame rather than loops.

Code from my MainActivity.java below

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.VideoView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        VideoView videoView = findViewById(R.id.videoView);
        Uri uri=Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.hab2);
        videoView.setVideoURI(uri);
        videoView.requestFocus();

        videoView.start();
        videoView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                finish();
            }
        });    }
}

You can handle easily if you use MediaPlayer

videoView.setOnPreparedListener(new OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mediaPlayer.setLooping(true);
    }
});

If you want to start the video after completing, then using setOnCompletionListener on the VideoView .

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

    final VideoView videoView = findViewById(R.id.videoView);

    Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.hab2);

    videoView.setVideoURI(uri);
    videoView.requestFocus();

    // TODO: Add these lines of code.
    videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            // TODO: When the video is completed, we will star it again.
            videoView.start();
        }
    });

    videoView.start();

    videoView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM