安卓Andriod使用入门(十九)【视频播放列表】
来源:互联网 发布:人工智能畅销书 编辑:程序博客网 时间:2024/05/17 05:51
为明天做准备的最好方法就是集中你所有智慧,所有的热忱,把今天的工作做得尽善尽美,这就是你能应付未来的唯一方法。
MainActivity.java代码:
package siso.videolist;import android.content.pm.ActivityInfo;import android.content.res.Configuration;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.KeyEvent;import android.view.Window;public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initActions(); } private void initActions() { } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); return true; } } return super.onKeyUp(keyCode, event); }}
CustomMediaContoller.java
package siso.videolist;import android.app.Activity;import android.content.Context;import android.content.pm.ActivityInfo;import android.graphics.Bitmap;import android.graphics.PointF;import android.graphics.Rect;import android.media.AudioManager;import android.os.Handler;import android.os.Message;import android.util.DisplayMetrics;import android.util.Log;import android.view.GestureDetector;import android.view.MotionEvent;import android.view.Surface;import android.view.View;import android.view.WindowManager;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.MediaController;import android.widget.ProgressBar;import android.widget.RelativeLayout;import android.widget.SeekBar;import android.widget.TextView;import siso.videolist.media.IMediaController;import siso.videolist.media.IjkVideoView;import tv.danmaku.ijk.media.player.IMediaPlayer;/** * @Description ${控制器} */public class CustomMediaContoller implements IMediaController { private static final int SET_VIEW_HIDE = 1; private static final int TIME_OUT = 5000; private static final int MESSAGE_SHOW_PROGRESS = 2; private static final int PAUSE_IMAGE_HIDE = 3; private static final int MESSAGE_SEEK_NEW_POSITION = 4; private static final int MESSAGE_HIDE_CONTOLL = 5; private View itemView; private View view; private boolean isShow; private IjkVideoView videoView; private boolean isScroll; private SeekBar seekBar; AudioManager audioManager; private ProgressBar progressBar; private boolean isSound; private boolean isDragging; private boolean isPause; private boolean isShowContoller; private ImageView sound, full, play; private TextView time, allTime,seekTxt; private PointF lastPoint; private Context context; private ImageView pauseImage; private Bitmap bitmap; private GestureDetector detector; private RelativeLayout show; private VSeekBar brightness_seek, sound_seek; private LinearLayout brightness_layout, sound_layout; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case SET_VIEW_HIDE: isShow = false; itemView.setVisibility(View.GONE); break; case MESSAGE_SHOW_PROGRESS: setProgress(); if (!isDragging && isShow) { msg = obtainMessage(MESSAGE_SHOW_PROGRESS); sendMessageDelayed(msg, 1000); } break; case PAUSE_IMAGE_HIDE: pauseImage.setVisibility(View.GONE); break; case MESSAGE_SEEK_NEW_POSITION: if (newPosition >= 0) { videoView.seekTo((int) newPosition); newPosition = -1; } break; case MESSAGE_HIDE_CONTOLL: seekTxt.setVisibility(View.GONE); brightness_layout.setVisibility(View.GONE); sound_layout.setVisibility(View.GONE); break; } } }; public CustomMediaContoller(Context context, View view) { this.view = view; itemView = view.findViewById(R.id.media_contoller); this.videoView = (IjkVideoView) view.findViewById(R.id.main_video); itemView.setVisibility(View.GONE); isShow = false; isDragging = false; isShowContoller = true; this.context = context; audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); initView(); initAction(); } public void initView() { progressBar = (ProgressBar) view.findViewById(R.id.loading); seekBar = (SeekBar) itemView.findViewById(R.id.seekbar); allTime = (TextView) itemView.findViewById(R.id.all_time); time = (TextView) itemView.findViewById(R.id.time); full = (ImageView) itemView.findViewById(R.id.full); sound = (ImageView) itemView.findViewById(R.id.sound); play = (ImageView) itemView.findViewById(R.id.player_btn); pauseImage = (ImageView) view.findViewById(R.id.pause_image); brightness_layout = (LinearLayout) view.findViewById(R.id.brightness_layout); brightness_seek = (VSeekBar) view.findViewById(R.id.brightness_seek); sound_layout = (LinearLayout) view.findViewById(R.id.sound_layout); sound_seek = (VSeekBar) view.findViewById(R.id.sound_seek); show = (RelativeLayout) view.findViewById(R.id.show); seekTxt= (TextView) view.findViewById(R.id.seekTxt); } private void initAction() { sound_seek.setEnabled(false); brightness_seek.setEnabled(false); isSound = false; detector = new GestureDetector(context, new PlayGestureListener()); mMaxVolume = ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)) .getStreamMaxVolume(AudioManager.STREAM_MUSIC); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { String string = generateTime((long) (duration * progress * 1.0f / 100)); time.setText(string); } @Override public void onStartTrackingTouch(SeekBar seekBar) { setProgress(); isDragging = true; audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true); handler.removeMessages(MESSAGE_SHOW_PROGRESS); show(); handler.removeMessages(SET_VIEW_HIDE); } @Override public void onStopTrackingTouch(SeekBar seekBar) { isDragging = false; videoView.seekTo((int) (duration * seekBar.getProgress() * 1.0f / 100)); handler.removeMessages(MESSAGE_SHOW_PROGRESS); audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false); isDragging = false; handler.sendEmptyMessageDelayed(MESSAGE_SHOW_PROGRESS, 1000); show(); } }); view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (detector.onTouchEvent(event)) return true; // 处理手势结束 switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_UP: endGesture(); break; } return false; } }); itemView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.e("custommedia", "event"); Rect seekRect = new Rect(); seekBar.getHitRect(seekRect); if ((event.getY() >= (seekRect.top - 50)) && (event.getY() <= (seekRect.bottom + 50))) { float y = seekRect.top + seekRect.height() / 2; //seekBar only accept relative x float x = event.getX() - seekRect.left; if (x < 0) { x = 0; } else if (x > seekRect.width()) { x = seekRect.width(); } MotionEvent me = MotionEvent.obtain(event.getDownTime(), event.getEventTime(), event.getAction(), x, y, event.getMetaState()); return seekBar.onTouchEvent(me); } return false; } }); videoView.setOnInfoListener(new IMediaPlayer.OnInfoListener() { @Override public boolean onInfo(IMediaPlayer mp, int what, int extra) { Log.e("setOnInfoListener", what + ""); switch (what) { case IMediaPlayer.MEDIA_INFO_BUFFERING_START: //开始缓冲 if (progressBar.getVisibility() == View.GONE) progressBar.setVisibility(View.VISIBLE); break; case IMediaPlayer.MEDIA_INFO_BUFFERING_END: //开始播放 progressBar.setVisibility(View.GONE); break; case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:// statusChange(STATUS_PLAYING); progressBar.setVisibility(View.GONE); break; case IMediaPlayer.MEDIA_INFO_AUDIO_RENDERING_START: progressBar.setVisibility(View.GONE); break; } return false; } }); sound.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isSound) { //静音 sound.setImageResource(R.mipmap.sound_mult_icon); audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true); } else { //取消静音 sound.setImageResource(R.mipmap.sound_open_icon); audioManager.setStreamMute(AudioManager.STREAM_MUSIC, false); } isSound = !isSound; } }); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (videoView.isPlaying()) { pause(); } else { reStart(); } } }); full.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("full", "full"); if (getScreenOrientation((Activity) context) == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } }); } public void start() { pauseImage.setVisibility(View.GONE); itemView.setVisibility(View.GONE); play.setImageResource(R.mipmap.video_stop_btn); progressBar.setVisibility(View.VISIBLE); } public void pause() { play.setImageResource(R.mipmap.video_play_btn); videoView.pause(); bitmap = videoView.getBitmap(); if (bitmap != null) { pauseImage.setImageBitmap(bitmap); pauseImage.setVisibility(View.VISIBLE); } } public void reStart() { play.setImageResource(R.mipmap.video_stop_btn); videoView.start(); if (bitmap != null) { handler.sendEmptyMessageDelayed(PAUSE_IMAGE_HIDE, 100); bitmap.recycle(); bitmap = null;// pauseImage.setVisibility(View.GONE); } } private long duration; public void setShowContoller(boolean isShowContoller) { this.isShowContoller = isShowContoller; handler.removeMessages(SET_VIEW_HIDE); itemView.setVisibility(View.GONE); } public int getScreenOrientation(Activity activity) { int rotation = activity.getWindowManager().getDefaultDisplay().getRotation(); DisplayMetrics dm = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; int height = dm.heightPixels; int orientation; // if the device's natural orientation is portrait: if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && height > width || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && width > height) { switch (rotation) { case Surface.ROTATION_0: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; case Surface.ROTATION_90: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_180: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; break; case Surface.ROTATION_270: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; break; default: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; } } // if the device's natural orientation is landscape or if the device // is square: else { switch (rotation) { case Surface.ROTATION_0: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_90: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; case Surface.ROTATION_180: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; break; case Surface.ROTATION_270: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; break; default: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; } } return orientation; } @Override public void hide() { if (isShow) { handler.removeMessages(MESSAGE_SHOW_PROGRESS); isShow = false; handler.removeMessages(SET_VIEW_HIDE); itemView.setVisibility(View.GONE); } } @Override public boolean isShowing() { return isShow; } @Override public void setAnchorView(View view) { } @Override public void setEnabled(boolean enabled) { } @Override public void setMediaPlayer(MediaController.MediaPlayerControl player) { } @Override public void show(int timeout) { handler.sendEmptyMessageDelayed(SET_VIEW_HIDE, timeout); } @Override public void show() { if (!isShowContoller) return; isShow = true; progressBar.setVisibility(View.GONE); itemView.setVisibility(View.VISIBLE); handler.sendEmptyMessage(MESSAGE_SHOW_PROGRESS); show(TIME_OUT); } @Override public void showOnce(View view) { } private String generateTime(long time) { int totalSeconds = (int) (time / 1000); int seconds = totalSeconds % 60; int minutes = (totalSeconds / 60) % 60; int hours = totalSeconds / 3600; return hours > 0 ? String.format("%02d:%02d:%02d", hours, minutes, seconds) : String.format("%02d:%02d", minutes, seconds); } public void setVisiable() { show(); } private long setProgress() { if (isDragging) { return 0; } long position = videoView.getCurrentPosition(); long duration = videoView.getDuration(); this.duration = duration; if (!generateTime(duration).equals(allTime.getText().toString())) allTime.setText(generateTime(duration)); if (seekBar != null) { if (duration > 0) { long pos = 100L * position / duration; seekBar.setProgress((int) pos); } int percent = videoView.getBufferPercentage(); seekBar.setSecondaryProgress(percent); } String string = generateTime((long) (duration * seekBar.getProgress() * 1.0f / 100)); time.setText(string); return position; } private VedioIsPause vedioIsPause; public interface VedioIsPause { void pause(boolean pause); } public void setPauseImageHide() { pauseImage.setVisibility(View.GONE); } public class PlayGestureListener extends GestureDetector.SimpleOnGestureListener { private boolean firstTouch; private boolean volumeControl; private boolean seek; @Override public boolean onDown(MotionEvent e) { firstTouch = true; handler.removeMessages(SET_VIEW_HIDE); //横屏下拦截事件 if (getScreenOrientation((Activity) context) == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { return true; }else { return super.onDown(e); } } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float x = e1.getX() - e2.getX(); float y = e1.getY() - e2.getY(); if (firstTouch) { seek = Math.abs(distanceX) >= Math.abs(distanceY); volumeControl = e1.getX() < view.getMeasuredWidth() * 0.5; firstTouch = false; } if (seek) { onProgressSlide(-x / view.getWidth(),e1.getX()/view.getWidth()); } else { float percent = y / view.getHeight(); if (volumeControl) { onVolumeSlide(percent); } else { onBrightnessSlide(percent); } } return super.onScroll(e1, e2, distanceX, distanceY); } } private int volume = -1; private float brightness = -1; private long newPosition = 1; private int mMaxVolume; /** * 手势结束 */ private void endGesture() { volume = -1; brightness = -1f; if (newPosition >= 0) { handler.removeMessages(MESSAGE_SEEK_NEW_POSITION); handler.sendEmptyMessage(MESSAGE_SEEK_NEW_POSITION); } handler.removeMessages(MESSAGE_HIDE_CONTOLL); handler.sendEmptyMessageDelayed(MESSAGE_HIDE_CONTOLL, 500); } /** * 滑动改变声音大小 * * @param percent */ private void onVolumeSlide(float percent) { if (volume == -1) { volume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); if (volume < 0) volume = 0; }// hide(); int index = (int) (percent * mMaxVolume) + volume; if (index > mMaxVolume) index = mMaxVolume; else if (index < 0) index = 0; // 变更声音 audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0); if (sound_layout.getVisibility()==View.GONE) sound_layout.setVisibility(View.VISIBLE); // 变更进度条 int i = (int) (index * 1.0f / mMaxVolume * 100); if (i == 0) { sound.setImageResource(R.mipmap.sound_mult_icon); } else { sound.setImageResource(R.mipmap.sound_open_icon); } sound_seek.setProgress(i); } /** * 滑动跳转 * * @param percent 移动比例 * @param downPer 按下比例 */ private void onProgressSlide(float percent,float downPer) { long position = videoView.getCurrentPosition(); long duration = videoView.getDuration(); long deltaMax = Math.min(100 * 1000, duration - position); long delta = (long) (deltaMax * percent); newPosition = delta + position; if (newPosition > duration) { newPosition = duration; } else if (newPosition <= 0) { newPosition = 0; delta = -position; } int showDelta = (int) delta / 1000; Log.e("showdelta", ((downPer +percent)*100) + ""); if (showDelta != 0) { if (seekTxt.getVisibility()==View.GONE) seekTxt.setVisibility(View.VISIBLE); String current=generateTime(newPosition); seekTxt.setText(current+"/"+allTime.getText()); } } /** * 滑动改变亮度 * * @param percent */ private void onBrightnessSlide(float percent) { if (brightness < 0) { brightness = ((Activity) context).getWindow().getAttributes().screenBrightness; if (brightness <= 0.00f) { brightness = 0.50f; } else if (brightness < 0.01f) { brightness = 0.01f; } } Log.d(this.getClass().getSimpleName(), "brightness:" + brightness + ",percent:" + percent); WindowManager.LayoutParams lpa = ((Activity) context).getWindow().getAttributes(); lpa.screenBrightness = brightness + percent; if (lpa.screenBrightness > 1.0f) { lpa.screenBrightness = 1.0f; } else if (lpa.screenBrightness < 0.01f) { lpa.screenBrightness = 0.01f; } if (brightness_layout.getVisibility()==View.GONE) brightness_layout.setVisibility(View.VISIBLE); brightness_seek.setProgress((int) (lpa.screenBrightness * 100)); ((Activity) context).getWindow().setAttributes(lpa); }}
VideoItemData.java
package siso.videolist;import java.io.Serializable;public class VideoItemData implements Serializable { int type; String cover; int playCount; String title; String mp4_url; String ptime; String vid; int length; String videosource; public int getType() { return type; } public void setType(int type) { this.type = type; } public String getCover() { return cover; } public void setCover(String cover) { this.cover = cover; } public int getPlayCount() { return playCount; } public void setPlayCount(int playCount) { this.playCount = playCount; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getMp4_url() { return mp4_url; } public void setMp4_url(String mp4_url) { this.mp4_url = mp4_url; } public String getPtime() { return ptime; } public void setPtime(String ptime) { this.ptime = ptime; } public String getVid() { return vid; } public void setVid(String vid) { this.vid = vid; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } public String getVideosource() { return videosource; } public void setVideosource(String videosource) { this.videosource = videosource; } boolean isPlaying; public boolean isPlaying() { return isPlaying; } public void setPlaying(boolean playing) { isPlaying = playing; } int currentPositon; public int getCurrentPositon() { return currentPositon; } public void setCurrentPositon(int currentPositon) { this.currentPositon = currentPositon; }}
VideoListData.java
package siso.videolist;import java.io.Serializable;import java.util.List;public class VideoListData implements Serializable { private List<VideoItemData> list; public List<VideoItemData> getList() { return list; } public void setList(List<VideoItemData> list) { this.list = list; }}
VideoListLayout.java
package siso.videolist;import android.annotation.TargetApi;import android.app.Activity;import android.content.Context;import android.content.pm.ActivityInfo;import android.content.res.Configuration;import android.os.Build;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.util.AttributeSet;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.RelativeLayout;import com.google.gson.Gson;import java.io.BufferedReader;import java.io.InputStreamReader;import siso.videolist.media.IjkVideoView;import siso.videolist.media.VideoAdapter;import tv.danmaku.ijk.media.player.IMediaPlayer;public class VideoListLayout extends RelativeLayout { private RecyclerView videoList; private LinearLayoutManager mLayoutManager; private VideoAdapter adapter; private FrameLayout videoLayout; private int postion = -1; private int lastPostion = -1; private Context context; private VideoPlayView videoItemView; private FrameLayout fullScreen; private VideoListData listData; private RelativeLayout smallLayout; private ImageView close; public VideoListLayout(Context context) { super(context); initView(context); initActions(); } public VideoListLayout(Context context, AttributeSet attrs) { super(context, attrs); initView(context); initActions(); } public VideoListLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(context); initActions(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public VideoListLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); initView(context); initActions(); } private void initView(Context context){ LayoutInflater.from(context).inflate(R.layout.layout_video_list,this,true); this.context = context; mLayoutManager = new LinearLayoutManager(context); videoList = (RecyclerView) findViewById(R.id.video_list); videoList.setLayoutManager(mLayoutManager); adapter = new VideoAdapter(context); videoList.setAdapter(adapter); fullScreen = (FrameLayout) findViewById(R.id.full_screen); videoLayout = (FrameLayout) findViewById(R.id.layout_video); videoItemView = new VideoPlayView(context); String data = readTextFileFromRawResourceId(context, R.raw.video_list); listData = new Gson().fromJson(data, VideoListData.class); adapter.refresh(listData.getList()); smallLayout = (RelativeLayout) findViewById(R.id.small_layout); close = (ImageView) findViewById(R.id.close); } private void initActions() { close.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (videoItemView.isPlay()) { videoItemView.stop(); postion = -1; lastPostion = -1; videoLayout.removeAllViews(); smallLayout.setVisibility(View.GONE); } } }); smallLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { smallLayout.setVisibility(View.GONE); ((Activity)context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } }); videoItemView.setCompletionListener(new VideoPlayView.CompletionListener() { @Override public void completion(IMediaPlayer mp) { //播放完还原播放界面 if (smallLayout.getVisibility() == View.VISIBLE) { videoLayout.removeAllViews(); smallLayout.setVisibility(View.GONE); videoItemView.setShowContoller(true); } FrameLayout frameLayout = (FrameLayout) videoItemView.getParent(); videoItemView.release(); if (frameLayout != null && frameLayout.getChildCount() > 0) { frameLayout.removeAllViews(); View itemView = (View) frameLayout.getParent(); if (itemView != null) { itemView.findViewById(R.id.showview).setVisibility(View.VISIBLE); } } lastPostion = -1; } }); adapter.setClick(new VideoAdapter.onClick() { @Override public void onclick(int position) { VideoListLayout.this.postion = position; if (videoItemView.VideoStatus() == IjkVideoView.STATE_PAUSED) { if (position != lastPostion) { videoItemView.stop(); videoItemView.release(); } } if (smallLayout.getVisibility() == View.VISIBLE) { smallLayout.setVisibility(View.GONE); videoLayout.removeAllViews(); videoItemView.setShowContoller(true); } if (lastPostion != -1) { ViewGroup last = (ViewGroup) videoItemView.getParent();//找到videoitemview的父类,然后remove if (last != null) { last.removeAllViews(); View itemView = (View) last.getParent(); if (itemView != null) { itemView.findViewById(R.id.showview).setVisibility(View.VISIBLE); } } } if (videoItemView.getParent() != null) { ((ViewGroup) videoItemView.getParent()).removeAllViews(); } View view = videoList.findViewHolderForAdapterPosition(postion).itemView; FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.layout_video); frameLayout.removeAllViews(); frameLayout.addView(videoItemView); videoItemView.start(listData.getList().get(position).getMp4_url()); lastPostion = position; } }); videoList.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() { @Override public void onChildViewAttachedToWindow(View view) { int index = videoList.getChildAdapterPosition(view); view.findViewById(R.id.showview).setVisibility(View.VISIBLE); if (index == postion) { FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.layout_video); frameLayout.removeAllViews(); if (videoItemView != null && ((videoItemView.isPlay()) || videoItemView.VideoStatus() == IjkVideoView.STATE_PAUSED)) { view.findViewById(R.id.showview).setVisibility(View.GONE); } if (videoItemView.VideoStatus() == IjkVideoView.STATE_PAUSED) { if (videoItemView.getParent() != null) ((ViewGroup) videoItemView.getParent()).removeAllViews(); frameLayout.addView(videoItemView); return; } if (smallLayout.getVisibility() == View.VISIBLE && videoItemView != null && videoItemView.isPlay()) { smallLayout.setVisibility(View.GONE); videoLayout.removeAllViews(); videoItemView.setShowContoller(true); frameLayout.addView(videoItemView); } } } @Override public void onChildViewDetachedFromWindow(View view) { int index = videoList.getChildAdapterPosition(view); if (index == postion) { FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.layout_video); frameLayout.removeAllViews(); if (smallLayout.getVisibility() == View.GONE && videoItemView != null && videoItemView.isPlay()) { videoLayout.removeAllViews(); videoItemView.setShowContoller(false); videoLayout.addView(videoItemView); smallLayout.setVisibility(View.VISIBLE); } } } }); } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (videoItemView != null) { videoItemView.onChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) { fullScreen.setVisibility(View.GONE); videoList.setVisibility(View.VISIBLE); fullScreen.removeAllViews(); if (postion <= mLayoutManager.findLastVisibleItemPosition() && postion >= mLayoutManager.findFirstVisibleItemPosition()) { View view = videoList.findViewHolderForAdapterPosition(postion).itemView; FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.layout_video); frameLayout.removeAllViews(); frameLayout.addView(videoItemView); videoItemView.setShowContoller(true); } else { videoLayout.removeAllViews(); videoLayout.addView(videoItemView); videoItemView.setShowContoller(false); smallLayout.setVisibility(View.VISIBLE); } videoItemView.setContorllerVisiable(); } else { ViewGroup viewGroup = (ViewGroup) videoItemView.getParent(); if (viewGroup == null) return; viewGroup.removeAllViews(); fullScreen.addView(videoItemView); smallLayout.setVisibility(View.GONE); videoList.setVisibility(View.GONE); fullScreen.setVisibility(View.VISIBLE); } } else { adapter.notifyDataSetChanged(); videoList.setVisibility(View.VISIBLE); fullScreen.setVisibility(View.GONE); } } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (videoItemView==null) videoItemView=new VideoPlayView(context); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (videoLayout == null) return; if (smallLayout.getVisibility() == View.VISIBLE) { smallLayout.setVisibility(View.GONE); videoLayout.removeAllViews(); } if (postion != -1) { ViewGroup view = (ViewGroup) videoItemView.getParent(); if (view != null) { view.removeAllViews(); } } videoItemView.stop(); videoItemView.release(); videoItemView.onDestroy(); videoItemView = null; } public String readTextFileFromRawResourceId(Context context, int resourceId) { StringBuilder builder = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().openRawResource( resourceId))); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { builder.append(line).append("\n"); } } catch (Exception e) { throw new RuntimeException(e); } return builder.toString(); }}
VideoPlayView.java
package siso.videolist;import android.app.Activity;import android.content.Context;import android.content.pm.ActivityInfo;import android.content.res.Configuration;import android.media.MediaPlayer;import android.net.Uri;import android.os.Handler;import android.util.AttributeSet;import android.util.Log;import android.view.LayoutInflater;import android.view.OrientationEventListener;import android.view.View;import android.view.ViewGroup;import android.view.WindowManager;import android.widget.RelativeLayout;import siso.videolist.media.IjkVideoView;import tv.danmaku.ijk.media.player.IMediaPlayer;/** * Description 播放view */public class VideoPlayView extends RelativeLayout implements MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener { private CustomMediaContoller mediaController; private View player_btn, view; private IjkVideoView mVideoView; private Handler handler = new Handler(); private boolean isPause; private View rView; private Context mContext; private boolean portrait;// private OrientationEventListener orientationEventListener; public VideoPlayView(Context context) { super(context); mContext = context; initData(); initViews(); initActions(); } private void initData() { } private void initViews() { rView = LayoutInflater.from(mContext).inflate(R.layout.view_video_item, this, true); view = findViewById(R.id.media_contoller); mVideoView = (IjkVideoView) findViewById(R.id.main_video); mediaController = new CustomMediaContoller(mContext, rView); mVideoView.setMediaController(mediaController); mVideoView.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() { @Override public void onCompletion(IMediaPlayer mp) { view.setVisibility(View.GONE); if (mediaController.getScreenOrientation((Activity) mContext) == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { //横屏播放完毕,重置 ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); ViewGroup.LayoutParams layoutParams = getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; setLayoutParams(layoutParams); } if (completionListener != null) completionListener.completion(mp); } }); } private void initActions() { /*orientationEventListener = new OrientationEventListener(mContext) { @Override public void onOrientationChanged(int orientation) { Log.e("onOrientationChanged", "orientation"); if (orientation >= 0 && orientation <= 30 || orientation >= 330 || (orientation >= 150 && orientation <= 210)) { //竖屏 if (portrait) { ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); orientationEventListener.disable(); } } else if ((orientation >= 90 && orientation <= 120) || (orientation >= 240 && orientation <= 300)) { if (!portrait) { ((Activity) mContext).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); orientationEventListener.disable(); } } } };*/ } public boolean isPlay() { return mVideoView.isPlaying(); } public void pause() { if (mVideoView.isPlaying()) { mVideoView.pause(); } else { mVideoView.start(); } } public void start(String path) { Uri uri = Uri.parse(path); if (mediaController != null) mediaController.start(); if (!mVideoView.isPlaying()) { mVideoView.setVideoURI(uri); mVideoView.start(); } else { mVideoView.stopPlayback(); mVideoView.setVideoURI(uri); mVideoView.start(); } } public void start(){ if (mVideoView.isPlaying()){ mVideoView.start(); } } public void setContorllerVisiable(){ mediaController.setVisiable(); } public void seekTo(int msec){ mVideoView.seekTo(msec); } public void onChanged(Configuration configuration) { portrait = configuration.orientation == Configuration.ORIENTATION_PORTRAIT; doOnConfigurationChanged(portrait); } public void doOnConfigurationChanged(final boolean portrait) { if (mVideoView != null) { handler.post(new Runnable() { @Override public void run() { setFullScreen(!portrait); if (portrait) { ViewGroup.LayoutParams layoutParams = getLayoutParams(); layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT; layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT; Log.e("handler", "400"); setLayoutParams(layoutParams); requestLayout(); } else { int heightPixels = ((Activity) mContext).getResources().getDisplayMetrics().heightPixels; int widthPixels = ((Activity) mContext).getResources().getDisplayMetrics().widthPixels; ViewGroup.LayoutParams layoutParams = getLayoutParams(); layoutParams.height = heightPixels; layoutParams.width = widthPixels; Log.e("handler", "height==" + heightPixels + "\nwidth==" + widthPixels); setLayoutParams(layoutParams); } } });// orientationEventListener.enable(); } } public void stop() { if (mVideoView.isPlaying()) { mVideoView.stopPlayback(); } } public void onDestroy() { handler.removeCallbacksAndMessages(null);// orientationEventListener.disable(); } private void setFullScreen(boolean fullScreen) { if (mContext != null && mContext instanceof Activity) { WindowManager.LayoutParams attrs = ((Activity) mContext).getWindow().getAttributes(); if (fullScreen) { attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN; ((Activity) mContext).getWindow().setAttributes(attrs); ((Activity) mContext).getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } else { attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN); ((Activity) mContext).getWindow().setAttributes(attrs); ((Activity) mContext).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } } } public void setShowContoller(boolean isShowContoller) { mediaController.setShowContoller(isShowContoller); } @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { } @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { return false; } public long getPalyPostion() { return mVideoView.getCurrentPosition(); } public void release() { mVideoView.release(true); } public int VideoStatus() { return mVideoView.getCurrentStatue(); } private CompletionListener completionListener; public void setCompletionListener(CompletionListener completionListener) { this.completionListener = completionListener; } public interface CompletionListener { void completion(IMediaPlayer mp); }}
VSeekBar.java
package siso.videolist;import android.annotation.TargetApi;import android.content.Context;import android.graphics.Canvas;import android.os.Build;import android.util.AttributeSet;import android.widget.SeekBar;/** * Description 垂直seekbar */public class VSeekBar extends SeekBar { public VSeekBar(Context context, AttributeSet attrs) { super(context, attrs); } public VSeekBar(Context context) { super(context); } public VSeekBar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public VSeekBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected synchronized void onDraw(Canvas canvas) { canvas.rotate(-90); canvas.translate(-getHeight(),0); super.onDraw(canvas); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(h, w, oldw, oldh); } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(heightMeasureSpec, widthMeasureSpec); setMeasuredDimension(getMeasuredHeight(),getMeasuredWidth()); } @Override public synchronized void setProgress(int progress) { super.setProgress(progress); }}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="siso.videolist"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:configChanges="keyboardHidden|orientation|screenSize|layoutDirection" android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
build.gradle
apply plugin: 'com.android.application'android { compileSdkVersion 23 buildToolsVersion "23.0.1" defaultConfig { applicationId "siso.videolist" minSdkVersion 22 targetSdkVersion 22 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }}dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.0.1' compile 'com.android.support:recyclerview-v7:23.0.1' compile 'com.google.code.gson:gson:2.6.2' compile 'tv.danmaku.ijk.media:ijkplayer-java:0.5.1' compile 'tv.danmaku.ijk.media:ijkplayer-armv7a:0.5.1' compile 'tv.danmaku.ijk.media:ijkplayer-exo:0.5.1' compile 'tv.danmaku.ijk.media:ijkplayer-x86:0.5.1' compile 'tv.danmaku.ijk.media:ijkplayer-armv5:0.5.1'}
项目运行结果如图:
0 0
- 安卓Andriod使用入门(十九)【视频播放列表】
- Android 安卓使用MediaPlayer播放列表视频
- 安卓Andriod使用入门(一)【圆形Menu菜单】
- 安卓Andriod使用入门(二)【高仿安卓微信6.0】
- 安卓Andriod使用入门(三)【2048游戏】
- 安卓Andriod使用入门(四)【图片毛玻璃效果】
- 安卓Andriod使用入门(五)【分类侧滑菜单】
- 安卓Andriod使用入门(六)【动态GridView控件】
- 安卓Andriod使用入门(七)【Android日历控件】
- 安卓Andriod使用入门(八)【联动ListView】
- 安卓Andriod使用入门(九)【悬浮窗菜单】
- 安卓Andriod使用入门(十一)【下拉刷新】
- 安卓Andriod使用入门(十二)【网络爬虫】
- 安卓Andriod使用入门(十四)【滑动布局】
- 安卓Andriod使用入门(二十)【颜色对话框】
- 安卓Andriod使用入门(二十三)【百度地图API】
- 安卓Andriod使用入门(二十四)【爬取网络小说】
- 安卓Andriod使用入门(二十五)【爬新闻】
- Android四大基本组件介绍与生命周期
- [后续] 一篇文章详解性能评估难点
- python 学习记录
- sql注入网站获取管理员密码第一天
- NGUI (三)加载txt文本内容
- 安卓Andriod使用入门(十九)【视频播放列表】
- 7.模块
- 结束一个线程
- Android 强大的图片加载缓存— Glide
- 分布式服务框架 Zookeeper -- 管理分布式环境中的数据
- vc++/mfc截图 保存和显示
- service的本地调用
- 33. Search in Rotated Sorted Array
- [js点滴]JavaScript之设备事件之横竖屏判断详解02