本文介绍了片段中的媒体控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Android Studio中制作媒体控制器,但使用片段而不是活动,我正在使用下面的代码,但这会给我以下错误:

I'm trying to make a media controller in Android studio but using a fragment instead of an activity, I'm using the code below, but it gives me the following error :

public class Tab1Helloworld extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab1helloworld, container, false);
        return rootView;


        VideoView video = (VideoView)rootView.findViewById(R.id.videoView);

        video.requestFocus();

        String videopath = "android.resource://com.r.teamkape.kiddiecodiel/" + R.raw.helloworldvid;

        video.setVideoURI(Uri.parse(videopath));

        video.setMediaController(new MediaController(this)); //error in (this)[enter image description here][1]

        video.requestFocus();
        video.start();
    }
}

推荐答案

@xhen,使用下面的代码效果很好,

@xhen, Use below code this works perfect,

在xml布局中添加此

<sg.xyz.test.util.CustomVideoView
    android:id="@+id/videoview"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentTop="true"
     />

在您的Fragment类中称这些方法

 private MediaController mediaController;
 private Uri uri;

 public void setupVideo(){
 if (mediaController == null) {
                mediaController = new
                        MediaController(mContext);

                mediaController.setAnchorView(mBinding.videoview);
                mBinding.videoview.setMediaController(mediaController);
            }
            try {
                uri = Util.buildURiPath(resourceID);
                mBinding.videoview.setVideoURI(uri);

            } catch (Exception e) {
                Logger.debug("Error: " + e.getMessage());
                e.printStackTrace();
            }
            mBinding.videoview.requestFocus();
            mBinding.imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    mBinding.videoview.start();

                    mBinding.imageView.setVisibility(View.INVISIBLE);

                }
            });
            mBinding.videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {

                    mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                        @Override
                        public void onVideoSizeChanged(MediaPlayer mediaPlayer, int width, int height) {
                            mediaController.setAnchorView(mBinding.videoview);
                        }
                    });
                    Logger.debug("Duration = " +
                            mBinding.videoview.getDuration());

                }
            });
            mBinding.videoview.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    AlertDialogFactory.buildAlertDialog(mContext, 0, R.string.video_playing_error).show();
                    return false;
                }
            });
 }


public static Uri buildURiPath(int resourceID)
{
    String uriPath = String.valueOf(Uri.parse("android.resource://" + LoginActivity.PACKAGE_NAME + "/"
            +resourceID));
    Uri uri = Uri.parse(uriPath);
    return uri;
}

将此mBinding.videoview替换为您的video对象.现在,创建CustomVideoView

Replace this mBinding.videoview with your video object that's it.Now, Create CustomVideoView class

public class CustomVideoView extends VideoView {

private int width;
private int height;
private Context context;
private VideoSizeChangeListener listener;
private boolean isFullscreen;

public CustomVideoView(Context context) {
    super(context);
    init(context);
}

public CustomVideoView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(context);
}

/**
 * get video screen width and height for calculate size
 *
 * @param context Context
 */
private void init(Context context) {
    this.context = context;
    setScreenSize();
}

/**
 * calculate real screen size
 */
private void setScreenSize() {
    Display display = ((Activity) context).getWindowManager().getDefaultDisplay();

    if (Build.VERSION.SDK_INT >= 17) {
        //new pleasant way to get real metrics
        DisplayMetrics realMetrics = new DisplayMetrics();
        display.getRealMetrics(realMetrics);
        width = realMetrics.widthPixels;
        height = realMetrics.heightPixels;

    } else if (Build.VERSION.SDK_INT >= 14) {
        //reflection for this weird in-between time
        try {
            Method mGetRawH = Display.class.getMethod("getRawHeight");
            Method mGetRawW = Display.class.getMethod("getRawWidth");
            width = (Integer) mGetRawW.invoke(display);
            height = (Integer) mGetRawH.invoke(display);
        } catch (Exception e) {
            //this may not be 100% accurate, but it's all we've got
            width = display.getWidth();
            height = display.getHeight();
        }

    } else {
        //This should be close, as lower API devices should not have window navigation bars
        width = display.getWidth();
        height = display.getHeight();
    }

    // when landscape w > h, swap it
    if (width > height) {
        int temp = width;
        width = height;
        height = temp;
    }
}

/**
 * set video size change listener
 *
 */
public void setVideoSizeChangeListener(VideoSizeChangeListener listener) {
    this.listener = listener;
}

public interface VideoSizeChangeListener {
    /**
     * when landscape
     */
    void onFullScreen();

    /**
     * when portrait
     */
    void onNormalSize();
}

@Override
public void setVideoURI(Uri uri) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(this.getContext(), uri);
    width = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
    height = Integer.parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
    super.setVideoURI(uri);
    super.setVideoURI(uri);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // full screen when landscape
        setSize(height, width);
        if (listener != null) listener.onFullScreen();
        isFullscreen = true;
    } else {
        // height = width * 9/16
        setSize(width, width * 9 / 16);
        if (listener != null) listener.onNormalSize();
        isFullscreen = false;
    }
}

/**
 * @return true: fullscreen
 */
public boolean isFullscreen() {
    return isFullscreen;
}

/**
 * set video sie
 *
 * @param w Width
 * @param h Height
 */
private void setSize(int w, int h) {
    setMeasuredDimension(w, h);
    getHolder().setFixedSize(w, h);
}
}

这篇关于片段中的媒体控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-19 19:32