boo-urns
boo-urns

Reputation: 10376

Adding VideoView to an XML layout

I would like to programmatically add a VideoView to a LinearLayout. The LinearLayout has an id of "main".

Referencing this SO question Video Streaming and Android, I was able to get the video to show up and play, but what if I wanted to create a new VideoView on the fly and add it to the layout?

This is the XML I am trying to "copy" programmatically:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/main"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent">
<VideoView android:id="@+id/your_video_view"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_gravity="center"
/>
</LinearLayout>

Here is how I tried to accomplish the same thing programmatically:

VideoView videoView = new VideoView(this);
LinearLayout layout = (LinearLayout)findViewById(R.id.main);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.addView(videoView, params);

The problem is that the video doesn't show up at all! With VideoView declared in XML, everything works fine, but programmatically, it doesn't work at all.

To be clear, I do not want to have a VideoView defined in the XML file when I am doing it programmatically.

Upvotes: 7

Views: 16436

Answers (1)

Lasse Samson
Lasse Samson

Reputation: 1752

I am not quite sure why your code is not working, but I can provide an example from one of my projects, where I inflate a VideoView and add it to a FrameLayout which is placed inside a LinearLayout. I control my video though a MediaController.

Here is the XML for my FrameLayout:

<FrameLayout
    android:id="@+id/videoFrameLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
</FrameLayout>

In the res/layout I have an XML file just containing a VideoView:

<?xml version="1.0" encoding="utf-8"?>
<VideoView 
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/your_video_view"
android:layout_height="fill_parent"
android:layout_width="fill_parent" />

To add it programmatically we need an inflater and the frame:

inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
videoFrame = (FrameLayout)findViewById(R.id.videoFrameLayout);

When I want to display the video and play it I use the following code:

videoView = (VideoView) inflater.inflate(R.layout.your_video_view, null);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoPath(FilePathHere);
videoFrame.addView(videoView);
videoView.start();

I hope this can be of some help to you until someone is able to answer your question :-)

Upvotes: 7

Related Questions