Android Custom Player Control videoview_android

Source: Internet
Author: User
Tags rewind

Introduced

Recently to use the player to do a simple video playback function, began to learn videoview, in the screen switch at the same time encountered a bit of trouble, but after the information is finally resolved. In the write Videoview play video when the definition of the control of the code is written in the actvity, write a look I code good chaos, so I wrote a custom player control, to support the specified size, can be screen switch, manual sliding fast forward to the fast back. Okay, here we go.

The effect picture is a bit card, I don't know why ...

Videoview Introduction

This is our implementation of video playback of the main control, detailed introduction everyone Baidu go to see, here are several commonly used methods.

Used to play video files. The Videoview class can read images from different sources (such as resource files or content providers), calculate and maintain the screen size of the video to fit any layout manager, and provide display options such as scaling, shading, and so on.

Several methods commonly used in Videoview

public int getduration ()

Total time to get the video played

public int GetCurrentPosition ()

To get the current position, we can use to set the display of playback time

public int GetCurrentPosition ()

To get the current position, we can use to set the display of playback time

public int Pause ()

Pause Playback

public int Seekto ()

To set the playback position, we use it when we're always fast forward.

public int Setoncompletionlistener (Mediaplayer.oncompletionlistener l)

Registers a callback function that is called when the media file has finished playing.

public int Setonerrorlistener (Mediaplayer.onerrorlistener l)

Registers a callback function that is invoked when an error occurs during Setup or playback. If no callback function is specified, or the callback function returns False, a dialog is played to prompt the user not to play

public void Setonpreparedlistener (Mediaplayer.onpreparedlistener l)

Registers a callback function that is called when the media file is loaded and can be played.

public void Setvideouri (URI uri)

Set the video source to play, or you can specify a local file with Setvideopath

public void Start ()

Start playing

Getholder (). Setfixedsize (Width,height);

Set the resolution of the videoview, if our videoview at the beginning of the playback is a vertical screen, when the horizontal screen when we changed the Videoview layout size, we need this method to reset its resolution, Otherwise you will notice that the video part of the Videoview inside is still the same size after the change.

Custom player Ideas

Say is a custom, in fact, it is just that these videoview and used to display the other controls together, and then in the internal processing of its event interaction, we have to do is the following steps: 1, write the layout of the entire space. 2. Get the individual small controls inside the entire control within the custom control, and set some initialization events for them. 3, according to your own logic and want to achieve the effect of writing your own event processing, you need to interact with the outside to provide methods and interface slightly. Finally, the test effect is used. OK, let's follow the 4 steps here to realize it!

Concrete implementation

1, the first step, write your own layout file

The desired effect is to put a status bar at the bottom of the display time information, playback progress, into the full screen, in the middle of a fast forward to the status of fast, layout code as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <framelayout xmlns:android= "http://schemas.android.com/apk/res/"
Android "android:id=" @+id/viewbox "android:layout_width=" match_parent "android:layout_height=" Wrap_content " android:descendantfocusability= "Beforedescendants" > <com.qiangyu.test.commonvideoview.myvideoview android: Id= "@+id/videoview" android:layout_width= "match_parent" android:layout_height= "match_parent"/>//Bottom status bar < LinearLayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" Horizontal "android:background=" #CC282828 "android:padding=" 3dip "android:id=" @+id/videocontrollerlayout "Android: gravity= "center" android:layout_gravity= "Bottom" > <linearlayout android:layout_width= "wrap_content" Android: layout_height= "match_parent" android:gravity= "center" android:id= "@+id/videopausebtn" android:paddingright= "10dip "android:paddingleft=" 10DP "> <imageview android:layout_width=" 22DP "android:layout_height=" 22DP "AndroiD:id= "@+id/videopauseimg"/> </LinearLayout> <linearlayout android:layout_width= "Fill_parent" Android: layout_height= "Wrap_content" android:layout_weight= "1" android:orientation= "Horizontal"
0dip "> <seekbar android:layout_width=" fill_parent "android:id=" @+id/videoseekbar "android:layout_weight=" "1" Style= "@android: Style/widget.holo.seekbar" android:layout_height= "wrap_content"/> <textview android:layout_ Width= "Wrap_content" android:layout_height= "fill_parent" android:gravity= "center" android:text= "00:00" Android: Textsize= "12DP" android:id= "@+id/videocurtime" android:textcolor= "#FFF"/> <textview android:layout_width= " Wrap_content "android:layout_height=" match_parent "android:gravity=" center "android:textsize=" 12DP "Android: Textcolor= "#FFF" android:text= "/"/> <textview android:layout_width= "wrap_content" android:layout_height= " Fill_parent "android:gravity=" center "android:text=" 00:00 "android:textsize=" 12DP "android:id=" @+id/videotOtaltime "android:textcolor=" #FFF "android:layout_marginright=" 10DP "/> </LinearLayout> <linearlayout
Android:id= "@+id/screen_status_btn" android:layout_width= "wrap_content" android:layout_height= "Match_parent" android:gravity= "center" > <imageview android:id= "@+id/screen_status_img" android:layout_width= "wrap_content "Android:layout_height=" wrap_content "android:src=" @mipmap/iconfont_enter_32/> </LinearLayout> </ Linearlayout>//videoview in the middle of the Start button and progress bar as well as fast forward rewind prompt <progressbar android:layout_width= "wrap_content" Android: layout_height= "wrap_content" android:layout_gravity= "center" android:id= "@+id/progressbar" style= "@android: style/
Widget.Holo.ProgressBar.Small "/> <imageview android:layout_width=" 30dip "android:layout_height=" 30dip " Android:id= "@+id/videoplayimg" android:layout_gravity= "center" android:src= "@mipmap/video_box_play"/> < LinearLayout android:id= "@+id/touch_view" android:layout_width= wrap_content "android:layout_height=" wrap_content"Android:orientation=" vertical "android:layout_gravity=" center "android:visibility=" Invisible "Android: paddingleft= "15DP" android:paddingright= "15DP" android:paddingtop= "5DP" android:paddingbottom= "5DP" Android: background= "#000" > <imageview android:layout_width= "fill_parent" android:layout_height= "Fill_parent" Android : layout_weight= "1" android:id= "@+id/touchstatusimg"/> <textview android:id= "@+id/touch_time" Android:layout_ Width= "Wrap_content" android:text= "25:00/59:00" android:textsize= "12SP" android:textcolor= "#fff" Android:layout_  height= "Wrap_content"/> </LinearLayout> </FrameLayout>

The layout is simple, Videoview is customized because when the layout changes, let Videoview retrieve the layout position and set its resolution to full screen. Videoview's code is as follows

public class Myvideoview extends Videoview {public
Myvideoview (context context, AttributeSet attrs, int defstyle) {
   super (context, attrs, Defstyle);
}
Public Myvideoview (context, AttributeSet attrs) {
Super (context, attrs);
}
Public Myvideoview {
super (context);
}
@Override
protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {
int width = getdefaultsize ( 0, Widthmeasurespec);
int height = getdefaultsize (0, heightmeasurespec);
This.getholder (). Setfixedsize (width,height);//Set Resolution
setmeasureddimension (width, height);
}

Okay, the layout's written. I'll take the second step, get the internal control initialization event

2, the second step, onfinishinflate () to get the internal control, do the initialization of the work

The Onfinishinflate method recalls the method when XML parsing is complete, usually the most common when making the combined control

@Override protected void Onfinishinflate () {super.onfinishinflate (); Initview ();} private void Initview () {View view =
Layoutinflater.from (context). Inflate (R.layout.common_video_view,null);
Viewbox = (framelayout) View.findviewbyid (R.id.viewbox);
Videoview = (Myvideoview) View.findviewbyid (R.id.videoview);
VIDEOPAUSEBTN = (linearlayout) View.findviewbyid (R.ID.VIDEOPAUSEBTN);
SCREENSWITCHBTN = (linearlayout) View.findviewbyid (R.ID.SCREEN_STATUS_BTN);
Videocontrollerlayout = (linearlayout) View.findviewbyid (r.id.videocontrollerlayout);
Touchstatusview = (linearlayout) View.findviewbyid (R.id.touch_view);
Touchstatusimg = (ImageView) View.findviewbyid (r.id.touchstatusimg);
Touchstatustime = (TextView) View.findviewbyid (r.id.touch_time);
Videocurtimetext = (TextView) View.findviewbyid (r.id.videocurtime);
Videototaltimetext = (TextView) View.findviewbyid (r.id.videototaltime);
Videoseekbar = (SeekBar) View.findviewbyid (R.id.videoseekbar); Videoplayimg = (ImageView) View.findviewbyid (r.id.VIDEOPLAYIMG);
Videoplayimg.setvisibility (GONE);
Videopauseimg = (ImageView) View.findviewbyid (r.id.videopauseimg);
ProgressBar = (ProgressBar) View.findviewbyid (R.id.progressbar);
Videopausebtn.setonclicklistener (this);
Videoseekbar.setonseekbarchangelistener (this);
Videopausebtn.setonclicklistener (this);
Videoview.setonpreparedlistener (this);
Videoview.setoncompletionlistener (this);
Screenswitchbtn.setonclicklistener (this);
Videoplayimg.setonclicklistener (this); Registers a callback function that is invoked when an error occurs during Setup or playback.
If no callback function is specified, or the callback function returns False,videoview, the user is notified that an error has occurred.
Videoview.setonerrorlistener (this);
Viewbox.setontouchlistener (this);
Viewbox.setonclicklistener (this);
AddView (view);  }

Very simple to do the code initialization and Videoview playback event registration, where the event to be handled by the Viewbox.setontouchlistener (this) registered Ontouch event, we have to write about sliding fast forward in the back of the effect, Videoseekbar.setonseekbarchangelistener (this); handle drag Seekbar Fast forward rewind.

3, the third step, the event, the effect of processing

Viewbox.setontouchlistener (this);

1, Ontouch in the implementation of fast forward fast retreat

@Override public boolean Ontouch (View v., motionevent event) {switch (event.getaction ()) {case Motionevent.action_down:/
/No playback time does not process if (!videoview.isplaying ()) {return false;} float Downx = Event.getrawx ();
TOUCHLASTX = Downx;
LOG.D ("Filmdetailactivity", "Downx" + downx);
Saves the current playback location with the event display this.position = Videoview.getcurrentposition ();
Break
Case Motionevent.action_move://Not playing when not processing if (!videoview.isplaying ()) {return false;} float CurrentX = Event.getrawx ();
float deltax = currentx-touchlastx;
float deltaxabs = Math.Abs (deltax); if (deltaxabs>1) {//forward move, fast-forward if (touchstatusview.getvisibility ()!=view.visible) {touchstatusview.setvisibility (
view.visible);
Show fast forward Time view} touchlastx = CurrentX;
LOG.D ("Filmdetailactivity", "DeltaX" +deltax); 
if (DeltaX > 1) {position + = Touchstep; if (position > duration) {position = duration;} touchposition = position;
Touchstatusimg.setimageresource (R.MIPMAP.IC_FAST_FORWARD_WHITE_24DP);
Int[] Time = getminuteandsecond (position); TouchstatUstime.settext (String.Format ("%02d:%02d/%s", time[0), time[1],formattotaltime); else if (DeltaX < 1) {//Rewind position-= touchstep; if (position < 0) {position = 0;} touchposition = Position T
Ouchstatusimg.setimageresource (R.MIPMAP.IC_FAST_REWIND_WHITE_24DP);
Int[] Time = getminuteandsecond (position);
Touchstatustime.settext (String.Format ("%02d:%02d/%s", time[0), time[1],formattotaltime);
Mvideoview.seekto (position);
}} break; Case MotionEvent.ACTION_UP:if (touchposition!=-1) {videoview.seekto (touchposition);//When you let go of your finger fast forward or rewind to the time position of the sliding decision
Touchstatusview.setvisibility (View.gone);
Touchposition =-1;
if (videocontrollershow) {return true;}}
Break
return false; }

2. Handle Seekbar Drag Events

@Override public
void onprogresschanged (SeekBar SeekBar, int progress, Boolean fromuser) {
int[] time = Getminute Andsecond (progress);
Videocurtimetext.settext (String.Format ("%02d:%02d", time[0), time[1));
Set the bottom time display
}
@Override public
void Onstarttrackingtouch (SeekBar SeekBar) {
videoview.pause ();
}
@Override public
void Onstoptrackingtouch (SeekBar SeekBar) {
Videoview.seekto ( Videoseekbar.getprogress ());
Videoview.start ();
Videoplayimg.setvisibility (view.invisible);
Videopauseimg.setimageresource (r.mipmap.icon_video_pause);
//Drag to the specified time position

3. Videoview Callback Event

@Override public
void onprepared (MediaPlayer MP) {
duration = videoview.getduration ();
Int[] Time = getminuteandsecond (duration);
Videototaltimetext.settext (String.Format ("%02d:%02d", time[0), time[1));
Formattotaltime = String.Format ("%02d:%02d", time[0), time[1]);
Videoseekbar.setmax (duration);
Progressbar.setvisibility (view.gone);
Mp.start ();
Videopausebtn.setenabled (true);
Videoseekbar.setenabled (true);
Videopauseimg.setimageresource (r.mipmap.icon_video_pause);
Timer.schedule (timertask, 0, 1000);
Initialization total time and so on some interface display, simultaneously with timer to modify time progress TextView
}
@Override public
void Oncompletion (MediaPlayer MP) {
videoview.seekto (0);
Videoseekbar.setprogress (0);
Videopauseimg.setimageresource (r.mipmap.icon_video_play);
Videoplayimg.setvisibility (view.visible);
}

There are other clicks on the time is not put, are paused, play, click to show hidden bottom status bar, Full-screen switch, and so on events. Here we are in the process of processing, and then we will be the video how to play it? To play we provide a way for the outside

Starts playing public
void start (String url) {
videopausebtn.setenabled (false);
Videoseekbar.setenabled (false);
Videoview.setvideouri (uri.parse (URL));
Videoview.start ();
}
Call public
void Setfullscreen () {
Touchstatusimg.setimageresource (r.mipmap.iconfont_exit) when entering full screen;
This.setlayoutparams (New Linearlayout.layoutparams (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
Videoview.requestlayout ();
}
Call public
void Setnormalscreen () {
Touchstatusimg.setimageresource (r.mipmap.iconfont_enter_32) when exiting the full screen;
This.setlayoutparams (New Linearlayout.layoutparams (viewgroup.layoutparams.match_parent,400));
Videoview.requestlayout ();

The Setfullscreen () and Setnormalscreen () provided above are required to change at the onconfigurationchanged (Configuration newconfig) of the activity. callback method inside call, also need to note that I write here is LinearLayout Layoutparams, so our custom view of the parent space if linearlayout, of course, you can also modify.

4, the use of the control

We just need to get space to call the Start method and then call Setfullscreen and Setnormalscreen in the Onconfigurationchanged method,

Layout

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
xmlns:app=" Http://schemas.android.com/apk/res-auto "
xmlns:tools=" http:// Schemas.android.com/tools "
android:layout_width=" match_parent "
android:layout_height=" Match_parent "
android:orientation= "vertical"
app:layout_behavior= "@string/appbar_scrolling_view_behavior"
tools : context= "com.qiangyu.test.commonvideoview.MainActivity" >
<android.support.v7.widget.toolbar
Android:id= "@+id/toolbar"
android:layout_width= "match_parent"
android:layout_height= "? attr/ Actionbarsize "
android:background=" attr/colorprimary "
app:popuptheme=" @style/apptheme.popupoverlay " />
<com.qiangyu.test.commonvideoview.commonvideoview
android:id= "@+id/common_videoview"
Android:layout_width= "Match_parent"
android:layout_height= "300DP"/>
</LinearLayout>

Activity Code

public class Mainactivity extends Appcompatactivity {
Commonvideoview videoview;
@Override
protected void onCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.content_main);
Toolbar Toolbar = (Toolbar) Findviewbyid (R.id.toolbar);
Setsupportactionbar (toolbar);
Videoview = (Commonvideoview) Findviewbyid (R.id.common_videoview);
Videoview.start ("Your Server video address");
}
@Override public void onconfigurationchanged (Configuration newconfig) {
super.onconfigurationchanged (newconfig );
if (newconfig.orientation = = configuration.orientation_landscape) {
videoview.setfullscreen ();
} else {
videoview.setnormalscreen ();}}}

Finally, to prevent your activity from being recreated at the bottom of the screen, don't forget to configure it in the Androidmanifest.xml file.

Android:configchanges= "Orientation|screensize|screenlayout", if you have doubts here you can refer to my article –> in-depth understanding of activity-life cycle

<activity
android:name= ". Mainactivity "
android:label=" @string/app_name "
android:theme=" @style/apptheme.noactionbar "
Android : configchanges= "Orientation|screensize|screenlayout" >
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

The above is a small set to share the Android custom player control Videoview knowledge, hope to help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.