Как я могу сделать видео в полноэкранном режиме на android webview?

Я не могу отображать видео в полноэкранном режиме с помощью приложения webview. Я пробовал некоторые решения, найденные в StackOverflow, но проблема все та же, в моем случае я не вижу кнопку полноэкранного режима при запуске видео на моем веб-сайте в WebView. В моем манифесте уже есть:

android:allowBackup="true"
android:hardwareAccelerated="true"

Это файл Java моей активности

public boolean doubleBackToExitPressedOnce = false;
private InterstitialAd interstitial;
private NavigationView navigationView;
public Timer AdTimer;
private boolean open_from_push = false;


public static final String PROPERTY_REG_ID = "notifyId";
private static final String PROPERTY_APP_VERSION = "appVersion";
SharedPreferences preferences;
String reg_cgm_id;
static final String TAG = "MainActivity";
private boolean first_fragment = false;
private double latitude;
private double longitude;

private VideoEnabledWebView webView;
private VideoEnabledWebChromeClient webChromeClient;


@Override
protected void onPause() {
    super.onPause();
    if (AdTimer != null) {
        AdTimer.cancel();
        AdTimer = null;
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.share_button:
            try {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
                String sAux = getString(R.string.share_text) + "\n";
                sAux = sAux + getString(R.string.share_link) + "\n";
                i.putExtra(Intent.EXTRA_TEXT, sAux);
                startActivity(Intent.createChooser(i, "choose one"));
            } catch (Exception e) { //e.toString();
            }
            return true;
        case R.id.btn11:
            android.os.Process.killProcess(android.os.Process.myPid());
            finish();
        default:
            return super.onOptionsItemSelected(item);
    }
}

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

    preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    if (getString(R.string.rtl_version).equals("true")) {
        getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
    }

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            } else {
                drawer.openDrawer(GravityCompat.START);
            }
        }
    });

    // Go to first fragment
    Intent intent = getIntent();
    if (intent.getExtras() != null && intent.getExtras().getString("link", null) != null && !intent.getExtras().getString("link", null).equals("")) {
        open_from_push = true;
        String url = null;
        if (intent.getExtras().getString("link").contains("http")) {
            url = intent.getExtras().getString("link");
        } else {
            url = "http://" + intent.getExtras().getString("link");
        }

        Bundle bundle = new Bundle();
        bundle.putString("type", "url");
        bundle.putString("url", url);
        Fragment fragment = new FragmentWebInteractive();
        fragment.setArguments(bundle);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment, "FragmentWebInteractive").commit();
        first_fragment = true;

    } else if (savedInstanceState == null) {
        Bundle bundle = new Bundle();
        bundle.putString("type", getString(R.string.home_type));
        bundle.putString("url", getString(R.string.home_url));
        Fragment fragment = new FragmentWebInteractive();
        fragment.setArguments(bundle);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment, "FragmentWebInteractive").commit();
        first_fragment = true;
    }


    // -------------------------------  AdMob Banner ------------------------------------------------------------
    AdView adView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
    adView.loadAd(adRequest);

    // -------------------------------- AdMob Interstitial ----------------------------
    // Prepare the Interstitial Ad
    interstitial = new InterstitialAd(MainActivity.this);
    // Insert the Ad Unit ID
    interstitial.setAdUnitId(getString(R.string.interstitial_ad_unit_id));

    // Load ads into Interstitial Ads
    interstitial.loadAd(adRequest);

    AdTimer = new Timer();

    // Prepare an Interstitial Ad Listener
    interstitial.setAdListener(new AdListener() {
        public void onAdLoaded() {
            // Call displayInterstitial() function with timer
            if (AdTimer != null) {
                AdTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                displayInterstitial();
                            }
                        });
                    }
                }, Integer.parseInt(getString(R.string.admob_interstiial_delay)));
            }
        }
    });


    if (preferences.getBoolean("pref_geolocation_update", true)) {

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            // create class object
            GPSTracker gps = new GPSTracker(MainActivity.this);

            // check if GPS enabled
            if (gps.canGetLocation()) {
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();


                int appVersion = getAppVersion(this);
                Log.i(TAG, "Saving regId on app version " + appVersion);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("latitude", "" + latitude);
                editor.putString("longitude", "" + longitude);
                editor.putString(PROPERTY_APP_VERSION, ""+appVersion);
                editor.commit();


                Log.d("GPS", "Latitude: " + latitude + ", Longitude: " + longitude);


            } else {
                // can't get location
                // GPS or Network is not enabled
                // Ask user to enable GPS/network in settings
                if (preferences.getBoolean("pref_gps_remember", false)) {
                    gps.showSettingsAlert();
                }
            }
        } else {
            // Request permission to the user
            ActivityCompat.requestPermissions(this, new String[]{
                    android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1
            );
        }
    }

А это XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipeContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<WebView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/webView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignParentTop="true" />

</android.support.v4.widget.SwipeRefreshLayout>

Может кто-нибудь сказать мне, что я могу сделать, чтобы решить эту проблему?

Обратите внимание, что я встроил видео iFrame на свой веб-сайт Wordpress.

попробуйте установить высоту и ширину WebView на match_parent

Akshay Katariya 11.04.2018 11:46

спасибо за комментарий, но не работает

AflamZone 11.04.2018 11:56
0
2
4 747
1

Ответы 1

Вам необходимо реализовать метод showCustomView & hideCustomView для WebChromeClient, также вам понадобится android:hardwareAccelerated="true" в вашем файле AndroidManifest.

Вот один пример от пользователя stackoverflow.

Ссылка на ресурс

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
        >
    <WebView
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/webView"
            android:layout_gravity="center"
            />
    <FrameLayout
            android:id="@+id/customViewContainer"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:visibility="gone"
            />
</LinearLayout>

video_progress.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/progress_indicator"
              android:orientation="vertical"
              android:layout_centerInParent="true"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <ProgressBar android:id="@android:id/progress"
                 style="?android:attr/progressBarStyleLarge"
                 android:layout_gravity="center"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"/>

    <TextView android:paddingTop="5dip"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="center"
              android:text="loading"
              android:textSize="14sp"
              android:textColor="?android:attr/textColorPrimary"/>
</LinearLayout>

MyActivity.java

package com.example.webview;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

public class MyActivity extends Activity {
    private WebView webView;
    private FrameLayout customViewContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    private View mCustomView;
    private myWebChromeClient mWebChromeClient;
    private myWebViewClient mWebViewClient;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
        webView = (WebView) findViewById(R.id.webView);

        mWebViewClient = new myWebViewClient();
        webView.setWebViewClient(mWebViewClient);

        mWebChromeClient = new myWebChromeClient();
        webView.setWebChromeClient(mWebChromeClient);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSaveFormData(true);
        webView.loadUrl("http://m.youtube.com");
    }

    public boolean inCustomView() {
        return (mCustomView != null);
    }

    public void hideCustomView() {
        mWebChromeClient.onHideCustomView();
    }

    @Override
    protected void onPause() {
        super.onPause();    //To change body of overridden methods use File | Settings | File Templates.
        webView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();    //To change body of overridden methods use File | Settings | File Templates.
        webView.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();    //To change body of overridden methods use File | Settings | File Templates.
        if (inCustomView()) {
            hideCustomView();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (inCustomView()) {
                hideCustomView();
                return true;
            }

            if ((mCustomView == null) && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    class myWebChromeClient extends WebChromeClient {
        private Bitmap mDefaultVideoPoster;
        private View mVideoProgressView;

        @Override
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
           onShowCustomView(view, callback);    //To change body of overridden methods use File | Settings | File Templates.
        }

        @Override
        public void onShowCustomView(View view,CustomViewCallback callback) {

            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            mCustomView = view;
            webView.setVisibility(View.GONE);
            customViewContainer.setVisibility(View.VISIBLE);
            customViewContainer.addView(view);
            customViewCallback = callback;
        }

        @Override
        public View getVideoLoadingProgressView() {

            if (mVideoProgressView == null) {
                LayoutInflater inflater = LayoutInflater.from(MyActivity.this);
                mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
            }
            return mVideoProgressView;
        }

        @Override
        public void onHideCustomView() {
            super.onHideCustomView();    //To change body of overridden methods use File | Settings | File Templates.
            if (mCustomView == null)
                return;

            webView.setVisibility(View.VISIBLE);
            customViewContainer.setVisibility(View.GONE);

            // Hide the custom view.
            mCustomView.setVisibility(View.GONE);

            // Remove the custom view from its container.
            customViewContainer.removeView(mCustomView);
            customViewCallback.onCustomViewHidden();

            mCustomView = null;
        }
    }

    class myWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);    //To change body of overridden methods use File | Settings | File Templates.
        }
    }

}

Я пробовал до этого ответа, но у меня не работает, спасибо

AflamZone 11.04.2018 12:15

Другие вопросы по теме