Programming/Android

안드로이드 스튜디오 비디오뷰 예제

fishersheep 2021. 8. 17. 14:17
반응형

 

main.xml

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="video test"
        android:textSize="40sp"
        android:gravity="center_horizontal"
        android:textColor="#000000"/>
    
    <VideoView
        android:id="@+id/video"
        android:layout_width="match_parent"
        android:layout_height="300dp"/>

</LinearLayout>

main.java

package com.cookandroid.videotest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final VideoView video = (VideoView)findViewById(R.id.video);
        Resources res = getResources();
        int id = res.getIdentifier("test","raw",getPackageName());

        Uri uri = Uri.parse("android.resource://com.cookandroid.videotest/"+id);

        video.setVideoURI(uri);

        video.start();

        MediaController controller = new MediaController(this);
        video.setMediaController(controller);
        video.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if(video.isPlaying()){
                    video.pause();
                    return false;
                }
                else {
                    video.start();
                    return false;
                }
            }
        });

    }
}

 

반응형