簡單說一下fragment,以及一些誤區
阿新 • • 發佈:2019-02-11
原來使用fragment的時候其Activity繼承的是FragmentActivity,所以當時就沒有發現漏洞,可是現在卻不然,突然發現自己又掉坑裡了,因為效果不是我要的,但是程式並沒有問題,只是程式適用的場景不同,好,現在來說一下,我在那翻船了,建議還是瞭解fragment http://blog.csdn.net/qq_23195583/article/details/45195127(這個適用情況比較多),下面說一下
說一下繼承FragmentActivity的
這個相當於管理fragment,這樣的話在其new的話可以在載入的時候進行相應的生命週期的操作package com.example.fanyafeng.laugh.activity; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.DisplayMetrics; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.TextView; import com.example.fanyafeng.laugh.R; import com.example.fanyafeng.laugh.fragment.EvaluateFragment; import com.example.fanyafeng.laugh.fragment.RecommendFragment; import java.util.ArrayList; import java.util.List; public class TestActivity extends FragmentActivity { private ViewPager test_viewpager; private List<Fragment> fragmentList; private int selectedColor, unSelectedColor; private Drawable selectedButton, unSelectedButton; private View RecommendView, EvaluateView; private TextView test_recommend, test_evaluate; private ImageView test_recommend_img, test_evaluate_img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); initView(); initData(); } private void initView() { unSelectedColor = getResources().getColor(R.color.black); selectedColor = getResources().getColor(R.color.red); selectedButton = getResources().getDrawable(R.drawable.video_playing_normal); unSelectedButton = getResources().getDrawable(R.drawable.video_playing_pressed); test_recommend_img = (ImageView) findViewById(R.id.test_recommend_img); test_evaluate_img = (ImageView) findViewById(R.id.test_evaluate_img); test_recommend = (TextView) findViewById(R.id.test_recommend); test_evaluate = (TextView) findViewById(R.id.test_evaluate); test_recommend.setOnClickListener(new MyOnClickListener(0)); test_evaluate.setOnClickListener(new MyOnClickListener(1)); initTextView(); initViewPager(); } private void initTextView() { test_recommend.setTextColor(selectedColor); test_recommend_img.setBackground(selectedButton); test_evaluate.setTextColor(unSelectedColor); test_evaluate_img.setBackground(unSelectedButton); } private void initData() { } private void initViewPager() { test_viewpager = (ViewPager) findViewById(R.id.test_viewpager); fragmentList = new ArrayList<Fragment>(); fragmentList.add(new RecommendFragment()); fragmentList.add(new EvaluateFragment()); test_viewpager.setAdapter(new OurPagerAdapter(getSupportFragmentManager(), fragmentList)); test_viewpager.setCurrentItem(0); test_viewpager.setOnPageChangeListener(new MyOnPageChangeListener()); } /** * 定義介面卡 */ class OurPagerAdapter extends FragmentPagerAdapter { private List<Fragment> fragmentList; private FragmentManager fragmentManager; public OurPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) { super(fm); this.fragmentList = fragmentList; } /** * 得到每個頁面 */ @Override public Fragment getItem(int arg0) { return (fragmentList == null || fragmentList.size() == 0) ? null : fragmentList.get(arg0); } public void setFragments(ArrayList<Fragment> fragments) { if (this.fragmentList != null) { FragmentTransaction ft = fragmentManager.beginTransaction(); for (Fragment f : this.fragmentList) { ft.remove(f); } ft.commit(); ft = null; fragmentManager.executePendingTransactions(); } this.fragmentList = fragments; notifyDataSetChanged(); } /** * 每個頁面的title */ @Override public CharSequence getPageTitle(int position) { return null; } /** * 頁面的總個數 */ @Override public int getCount() { return fragmentList == null ? 0 : fragmentList.size(); } } public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener { public void onPageScrollStateChanged(int index) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } public void onPageSelected(int index) { switch (index) { case 0: test_recommend.setTextColor(selectedColor); test_recommend_img.setBackground(selectedButton); test_evaluate.setTextColor(unSelectedColor); test_evaluate_img.setBackground(unSelectedButton); break; case 1: test_recommend.setTextColor(unSelectedColor); test_recommend_img.setBackground(unSelectedButton); test_evaluate.setTextColor(selectedColor); test_evaluate_img.setBackground(selectedButton); break; } } } private class MyOnClickListener implements View.OnClickListener { private int index = 0; public MyOnClickListener(int i) { index = i; } public void onClick(View v) { test_viewpager.setCurrentItem(index); } } }
來看被管理的fragment
這樣的話,每當載入相應的fragment就可以按照相應的生命週期走,而不是僅僅載入相應的xml上面的佈局,再來看繼承Activity的package com.example.fanyafeng.laugh.fragment; import android.app.Activity; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.example.fanyafeng.laugh.R; import com.example.fanyafeng.laugh.adapter.VideoListAdapter; import com.example.fanyafeng.laugh.bean.VideoListBean; import com.example.fanyafeng.laugh.util.L; import com.example.fanyafeng.laugh.util.PostUtil; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link RecommendFragment.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link RecommendFragment#newInstance} factory method to * create an instance of this fragment. */ public class RecommendFragment extends BaseFragment { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; private ListView recommend_listview; private VideoListAdapter videoListAdapter; private List<VideoListBean> videoListBeanList = new ArrayList<VideoListBean>(); private List<Map<String, Object>> videoInfoList = new ArrayList<Map<String, Object>>(); // private OnFragmentInteractionListener mListener; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment RecommendFragment. */ // TODO: Rename and change types and number of parameters public static RecommendFragment newInstance(String param1, String param2) { RecommendFragment fragment = new RecommendFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } public RecommendFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_recommend, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initView(); Thread loadThread = new Thread(new LoadThread()); loadThread.start(); initData(); } private void initView(){ recommend_listview=(ListView)getActivity().findViewById(R.id.recommend_listview); } private void initData(){ } class LoadThread implements Runnable { @Override public void run() { loadData(); } } private void loadData(){ Map<String,String> map=new LinkedHashMap<String,String>(); map.put("devicetype","android"); try { String backMsg = PostUtil.postData(BaseUrl+GetRecommendVideo, map); L.d("推薦列表具體內容",backMsg); } catch (IOException e) { e.printStackTrace(); } } // // TODO: Rename method, update argument and hook method into UI event // public void onButtonPressed(Uri uri) { // if (mListener != null) { // mListener.onFragmentInteraction(uri); // } // } // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // try { // mListener = (OnFragmentInteractionListener) activity; // } catch (ClassCastException e) { // throw new ClassCastException(activity.toString() // + " must implement OnFragmentInteractionListener"); // } // } // @Override // public void onDetach() { // super.onDetach(); // mListener = null; // } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ // public interface OnFragmentInteractionListener { // // TODO: Update argument type and name // public void onFragmentInteraction(Uri uri); // } }
下面的Activity裡面有其他的程式碼,大家稍微過濾小,我就不在這裡ctrl+d了
如果繼承的是Activity的話,只會載入相應的佈局,fragment不會進行相應的操作package com.example.fanyafeng.laugh.activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.Process; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; import com.baidu.cyberplayer.core.BVideoView; import com.baidu.cyberplayer.core.BVideoView.OnCompletionListener; import com.baidu.cyberplayer.core.BVideoView.OnErrorListener; import com.baidu.cyberplayer.core.BVideoView.OnInfoListener; import com.baidu.cyberplayer.core.BVideoView.OnPlayingBufferCacheListener; import com.baidu.cyberplayer.core.BVideoView.OnPreparedListener; import com.example.fanyafeng.laugh.R; import com.example.fanyafeng.laugh.fragment.EvaluateFragment; import com.example.fanyafeng.laugh.fragment.RecommendFragment; import com.example.fanyafeng.laugh.util.L; import com.example.fanyafeng.laugh.util.PostUtil; import com.example.fanyafeng.laugh.util.T; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; public class VideoViewPlayingActivity extends BaseNoActionbarActivity implements OnPreparedListener, OnCompletionListener, OnErrorListener, OnInfoListener, OnPlayingBufferCacheListener { private final String TAG = "VideoViewPlayingActivity"; private String mVideoSource = null; private ImageButton mPlaybtn = null; private ImageButton mPrebtn = null; private ImageButton mForwardbtn = null; private LinearLayout mController = null; private SeekBar mProgress = null; private TextView mDuration = null; private TextView mCurrPostion = null; private String url_info; /** * 記錄播放位置 */ private int mLastPos = 0; /** * 播放狀態 */ private enum PLAYER_STATUS { PLAYER_IDLE, PLAYER_PREPARING, PLAYER_PREPARED, } private PLAYER_STATUS mPlayerStatus = PLAYER_STATUS.PLAYER_IDLE; private BVideoView mVV = null; private EventHandler mEventHandler; private HandlerThread mHandlerThread; private final Object SYNC_Playing = new Object(); private WakeLock mWakeLock = null; private static final String POWER_LOCK = "VideoViewPlayingActivity"; private boolean mIsHwDecode = false; private final int EVENT_PLAY = 0; private final int UI_EVENT_UPDATE_CURRPOSITION = 1; private ViewPager video_playing_viewpager; private List<View> viewList; private FragmentManager fragmentManager; private TextView video_recommend, video_evaluate; private int selectedColor, unSelectedColor; private View RecommendView, EvaluateView; private Drawable selectedButton, unSelectedButton; private ImageView video_recommend_img, video_evaluate_img; class EventHandler extends Handler { public EventHandler(Looper looper) { super(looper); } @Override public void handleMessage(Message msg) { switch (msg.what) { case EVENT_PLAY: /** * 如果已經播放了,等待上一次播放結束 */ if (mPlayerStatus != PLAYER_STATUS.PLAYER_IDLE) { synchronized (SYNC_Playing) { try { SYNC_Playing.wait(); Log.v(TAG, "wait player status to idle"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 設定播放url */ mVV.setVideoPath(mVideoSource); /** * 續播,如果需要如此 */ if (mLastPos > 0) { mVV.seekTo(mLastPos); mLastPos = 0; } /** * 顯示或者隱藏緩衝提示 */ mVV.showCacheInfo(true); /** * 開始播放 */ mVV.start(); mPlayerStatus = PLAYER_STATUS.PLAYER_PREPARING; break; default: break; } } } Handler mUIHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { /** * 更新進度及時間 */ case UI_EVENT_UPDATE_CURRPOSITION: int currPosition = mVV.getCurrentPosition(); int duration = mVV.getDuration(); updateTextViewWithTimeFormat(mCurrPostion, currPosition); updateTextViewWithTimeFormat(mDuration, duration); mProgress.setMax(duration); mProgress.setProgress(currPosition); mUIHandler.sendEmptyMessageDelayed(UI_EVENT_UPDATE_CURRPOSITION, 200); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_video_view_playing); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, POWER_LOCK); Intent intent = this.getIntent(); url_info = intent.getStringExtra("url_info"); L.d(url_info); mIsHwDecode = getIntent().getBooleanExtra("isHW", false); Thread loadThread = new Thread(new LoadMore()); loadThread.start(); initTextView(); initUI(); initViewPager(); /** * 開啟後臺事件處理執行緒 */ mHandlerThread = new HandlerThread("event handler thread", Process.THREAD_PRIORITY_BACKGROUND); mHandlerThread.start(); // mEventHandler = new EventHandler(mHandlerThread.getLooper()); } private void initTextView() { unSelectedColor = getResources().getColor(R.color.black); selectedColor = getResources().getColor(R.color.black); selectedButton = getResources().getDrawable(R.drawable.video_playing_normal); unSelectedButton = getResources().getDrawable(R.drawable.video_playing_pressed); video_recommend = (TextView) findViewById(R.id.video_recommend); video_evaluate = (TextView) findViewById(R.id.video_evaluate); video_recommend_img = (ImageView) findViewById(R.id.video_recommend_img); video_evaluate_img = (ImageView) findViewById(R.id.video_evaluate_img); video_recommend.setTextColor(selectedColor); // video_recommend_img.setBackground(selectedButton); video_evaluate.setTextColor(unSelectedColor); // video_evaluate_img.setBackground(unSelectedButton); video_recommend.setOnClickListener(new MyOnClickListener(0)); video_evaluate.setOnClickListener(new MyOnClickListener(1)); } private class MyOnClickListener implements View.OnClickListener { private int index = 0; public MyOnClickListener(int i) { index = i; } public void onClick(View v) { video_playing_viewpager.setCurrentItem(index); } } private void initViewPager() { video_playing_viewpager = (ViewPager) findViewById(R.id.video_playing_viewpager); viewList = new ArrayList<View>(); LayoutInflater inflater = getLayoutInflater(); RecommendView = inflater.inflate(R.layout.fragment_recommend, null); EvaluateView = inflater.inflate(R.layout.fragment_evaluate, null); viewList.add(RecommendView); viewList.add(EvaluateView); video_playing_viewpager.setAdapter(new MyViewPagerAdapter(viewList)); video_playing_viewpager.setCurrentItem(0); video_playing_viewpager.setOnPageChangeListener(new VideoListOnPageChangeListener()); } public class VideoListOnPageChangeListener implements ViewPager.OnPageChangeListener { public void onPageScrollStateChanged(int index) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } public void onPageSelected(int index) { switch (index) { case 0: video_recommend.setTextColor(selectedColor); // video_recommend_img.setBackground(selectedButton); video_evaluate.setTextColor(unSelectedColor); // video_evaluate_img.setBackground(unSelectedButton); break; case 1: video_recommend.setTextColor(unSelectedColor); // video_recommend_img.setBackground(unSelectedButton); video_evaluate.setTextColor(selectedColor); // video_evaluate_img.setBackground(selectedButton); break; } } } public class MyViewPagerAdapter extends PagerAdapter { private List<View> mListViews; public MyViewPagerAdapter(List<View> mListViews) { this.mListViews = mListViews; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(mListViews.get(position)); } @Override public Object instantiateItem(ViewGroup container, int position) { container.addView(mListViews.get(position), 0); return mListViews.get(position); } @Override public int getCount() { return mListViews.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); } class LoadMore implements Runnable { @Override public void run() { getRealUrl(url_info); } } private void getRealUrl(String url_info) { Map<String, String> map = new LinkedHashMap<>(); map.put("url", url_info); try { String backMsg = PostUtil.postData(BaseUrl + GetRealUrl, map); try { JSONObject jsonObject = new JSONObject(backMsg); Message message = Message.obtain(); if (jsonObject.getInt("result") == 1) { JSONObject data = jsonObject.getJSONObject("data"); Bundle bundle = new Bundle(); bundle.putString("m3u8", data.getString("m3u8")); message.setData(bundle); message.what = 1; uiHandler.sendMessage(message); } else { message.what = 0; uiHandler.sendMessage(message); } } catch (JSONException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } Handler uiHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); Bundle bundle = msg.getData(); switch (msg.what) { case 0: T.showLong(VideoViewPlayingActivity.this, "視訊解析失敗"); break; case 1: mVideoSource = bundle.getString("m3u8"); mEventHandler = new EventHandler(mHandlerThread.getLooper()); mEventHandler.sendEmptyMessage(EVENT_PLAY); break; } } }; /** * 初始化介面 */ private void initUI() { mPlaybtn = (ImageButton) findViewById(R.id.play_btn); mPrebtn = (ImageButton) findViewById(R.id.pre_btn); mForwardbtn = (ImageButton) findViewById(R.id.next_btn); mController = (LinearLayout) findViewById(R.id.controlbar); mProgress = (SeekBar) findViewById(R.id.media_progress); mDuration = (TextView) findViewById(R.id.time_total); mCurrPostion = (TextView) findViewById(R.id.time_current); registerCallbackForControl(); /** * 設定ak及sk的前16位 */ BVideoView.setAKSK("kBSfVrlokXqK0cFDYoaRSXle", "MTzMwgYd4CLI5dtIFBY4RZmSW77RnKyD"); /** *獲取BVideoView物件 */ mVV = (BVideoView) findViewById(R.id.video_view); /** * 註冊listener */ mVV.setOnPreparedListener(this); mVV.setOnCompletionListener(this); mVV.setOnErrorListener(this); mVV.setOnInfoListener(this); /** * 設定解碼模式 */ mVV.setDecodeMode(mIsHwDecode ? BVideoView.DECODE_HW : BVideoView.DECODE_SW); } /** * 為控制元件註冊回撥處理函式 */ private void registerCallbackForControl() { mPlaybtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub if (mVV.isPlaying()) { mPlaybtn.setImageResource(R.drawable.play_btn_style); /** * 暫停播放 */ mVV.pause(); } else { mPlaybtn.setImageResource(R.drawable.pause_btn_style); /** * 繼續播放 */ mVV.resume(); } } }); /** * 實現切換示例 */ mPrebtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { /** * 如果已經播放了,等待上一次播放結束 */ if (mPlayerStatus != PLAYER_STATUS.PLAYER_IDLE) { mVV.stopPlayback(); } /** * 發起一次新的播放任務 */ if (mEventHandler.hasMessages(EVENT_PLAY)) mEventHandler.removeMessages(EVENT_PLAY); mEventHandler.sendEmptyMessage(EVENT_PLAY); } }); mForwardbtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub } }); OnSeekBarChangeListener osbc1 = new OnSeekBarChangeListener() { public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub //Log.v(TAG, "progress: " + progress); updateTextViewWithTimeFormat(mCurrPostion, progress); } public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub /** * SeekBar開始seek時停止更新 */ mUIHandler.removeMessages(UI_EVENT_UPDATE_CURRPOSITION); } public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub int iseekPos = seekBar.getProgress(); /** * SeekBark完成seek時執行seekTo操作並更新介面 * */ mVV.seekTo(iseekPos); Log.v(TAG, "seek to " + iseekPos); mUIHandler.sendEmptyMessage(UI_EVENT_UPDATE_CURRPOSITION); } }; mProgress.setOnSeekBarChangeListener(osbc1); } private void updateTextViewWithTimeFormat(TextView view, int second) { int hh = second / 3600; int mm = second % 3600 / 60; int ss = second % 60; String strTemp = null; if (0 != hh) { strTemp = String.format("%02d:%02d:%02d", hh, mm, ss); } else { strTemp = String.format("%02d:%02d", mm, ss); } view.setText(strTemp); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); /** * 在停止播放前 你可以先記錄當前播放的位置,以便以後可以續播 */ if (mPlayerStatus == PLAYER_STATUS.PLAYER_PREPARED) { mLastPos = mVV.getCurrentPosition(); mVV.stopPlayback(); } } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); Log.v(TAG, "onResume"); if (null != mWakeLock && (!mWakeLock.isHeld())) { mWakeLock.acquire(); } /** * 發起一次播放任務,當然您不一定要在這發起 */ // mEventHandler.sendEmptyMessage(EVENT_PLAY); } private long mTouchTime; private boolean barShow = true; @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub if (event.getAction() == MotionEvent.ACTION_DOWN) mTouchTime = System.currentTimeMillis(); else if (event.getAction() == MotionEvent.ACTION_UP) { long time = System.currentTimeMillis() - mTouchTime; if (time < 400) { updateControlBar(!barShow); } } return true; } public void updateControlBar(boolean show) { if (show) { mController.setVisibility(View.VISIBLE); } else { mController.setVisibility(View.INVISIBLE); } barShow = show; } @Override protected void onStop() { super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); /** * 退出後臺事件處理執行緒 */ mHandlerThread.quit(); } @Override public boolean onInfo(int what, int extra) { // TODO Auto-generated method stub switch (what) { /** * 開始緩衝 */ case BVideoView.MEDIA_INFO_BUFFERING_START: break; /** * 結束緩衝 */ case BVideoView.MEDIA_INFO_BUFFERING_END: break; default: break; } return true; } /** * 當前緩衝的百分比, 可以配合onInfo中的開始緩衝和結束緩衝來顯示百分比到介面 */ @Override public void onPlayingBufferCache(int percent) { // TODO Auto-generated method stub } /** * 播放出錯 */ @Override public boolean onError(int what, int extra) { // TODO Auto-generated method stub Log.v(TAG, "onError"); synchronized (SYNC_Playing) { SYNC_Playing.notify(); } mPlayerStatus = PLAYER_STATUS.PLAYER_IDLE; mUIHandler.removeMessages(UI_EVENT_UPDATE_CURRPOSITION); return true; } /** * 播放完成 */ @Override public void onCompletion() { // TODO Auto-generated method stub Log.v(TAG, "onCompletion"); synchronized (SYNC_Playing) { SYNC_Playing.notify(); } mPlayerStatus = PLAYER_STATUS.PLAYER_IDLE; mUIHandler.removeMessages(UI_EVENT_UPDATE_CURRPOSITION); } /** * 準備播放就緒 */ @Override public void onPrepared() { // TODO Auto-generated method stub Log.v(TAG, "onPrepared"); mPlayerStatus = PLAYER_STATUS.PLAYER_PREPARED; mUIHandler.sendEmptyMessage(UI_EVENT_UPDATE_CURRPOSITION); } }
具體的大家可以自己圖寫個demo體會一下