Adnan Mulla Adnan Mulla - 4 months ago 34
Android Question

How to play Video in Android on click?

I tried playing a Video from a remote URL & it works fine , the problem now is that the video starts playing automatically, I want the video to show up like a YouTube video with a play button in center & on clicking that the video should play .

public class Tabs extends Activity {
TabHost th;
VideoView video;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Create tabs using XML

video=(VideoView) findViewById(R.id.VideoView);
String path1="http://www.w3schools.com/html5/movie.mp4";
MediaController mc = new MediaController(this);
mc.setAnchorView(video);
mc.setMediaPlayer(video);
Uri uri=Uri.parse(path1);
video.setMediaController(mc);
video.setVideoURI(uri);
video.start();
}
}


Here is my code which works perfectly fine , but the video automatically starts playing , i need it to just show the first scene like YouTube video with a play button in center & on clicking that the video should start playing. Also it should show a thumbnail of the video

Answer

Setup the video player and URLs in the onCreate and do the actual playing by implementing onClickListener.

In your example (remember to import missing packages and create a button with ID of buttonStart):

public class Test extends Activity {
    TabHost th;
    VideoView video;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Create tabs using XML

        video = (VideoView) findViewById(R.id.VideoView);
        String path1 = "http://www.w3schools.com/html5/movie.mp4";
        MediaController mc = new MediaController(this);
        mc.setAnchorView(video);
        mc.setMediaPlayer(video);
        Uri uri = Uri.parse(path1);
        video.setMediaController(mc);
        video.setVideoURI(uri);
        Button buttonStart = (Button) findViewById(R.id.buttonStart);
        buttonStart.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                video.start();
            }

        });

    }
}

As for displaying the thumbnail, if you have its URL, you can start an Async task that will retrieve the remote image and overlay it over the video player (use FrameLayout to achieve overlaying Views). Then setup an onClickListener on the overlaying image (see the code on how it's done for a button, the same logic can be followed for an ImageView). Just make sure you set the ImageView to be clickable.