MediaControllerのレイアウトを変更可能にする
Androidでオーディオや動画を再生するアプリを作る場合、シークバーや停止・再生ボタンなどを自前で実装しても良いのですがそれだと結構面倒です。
そんな場合はMediaControllerを使うと、それらが初めから用意されているので、適当なVideoViewにセットするだけで使えて非常に楽です。
import android.widget.MediaController; import android.widget.VideoView; public class HogehogePlayerFragment extends Fragment implements MediaController.MediaPlayerControl{ private MediaController mMediaController; private VideoView mVideo; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View fv = inflater.inflate(R.layout.fragment_hogehogeplayer, container, false); mVideo = (VideoView)fv.findViewById(R.id.videoview_id); mMediaController = new MediaController(this.getActivity()) { @Override public void hide() { //Do not hide. } }; mMediaController.setMediaPlayer(this); // 適当な表示用 View の下にコントローラを表示させる。 mMediaController.setAnchorView(mVideo); : :
※こんなかんじ
しかし、そんな便利なMediaControllerなのですが、致命的な欠点が・・・。
レイアウトが固定されていて、変更ができないのです。
さあ困った・・・。
困り果ててGoogle先生とStackOverflow先生に聞いてみたところ、以下のサイトにたどり着きました。
Custom Android media controller
要は、MediaControllerを真似をして作ったクラス(VideoControllerView.java)をダウンロードして、layoutとアイコンとを一緒にProjectに放り込めって事らしいです。
ここで少しはまったのが、新しいクラスではsetAnchorView()に渡す引数がVideoViewからViewGroupに変わっていました。
なので、セットする方も以下のように変更。
※ダウンロードしたクラス名はCustomMediaControllerに変えてあります。
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment final View fv = inflater.inflate(R.layout.fragment_hogehogeplayer, container, false); mVideo = (FrameLayout)fv.findViewById(R.id.videoSurfaceContainer); mMediaController = new CustomMediaController(this.getActivity()) { @Override public void hide() { //Do not hide. } }; mMediaController.setMediaPlayer(this); // 適当な表示 View の下にコントローラを表示させる。 mMediaController.setAnchorView((FrameLayout) mVideo);
fragment_hogehogeplayer.xmlは以下のような感じ。
<FrameLayout android:id="@+id/videoSurfaceContainer" android:layout_width="match_parent" android:layout_height="wrap_content" > <VideoView android:id="@+id/videoview_id" android:layout_width="wrap_content" android:layout_height="match_parent" android:background="#ffffff"/> </FrameLayout>
FrameLayoutとViewGroupに互換性があるというのが肝でした。
※「ViewGroup」は「FrameLayout」の親クラス。