Example usage for android.view View setOnApplyWindowInsetsListener

List of usage examples for android.view View setOnApplyWindowInsetsListener

Introduction

In this page you can find the example usage for android.view View setOnApplyWindowInsetsListener.

Prototype

public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) 

Source Link

Document

Set an OnApplyWindowInsetsListener to take over the policy for applying window insets to this view.

Usage

From source file:com.google.samples.apps.ourstreets.view.ViewUtils.java

/**
 * Applies top window insets for a view.
 *
 * @param view The view to apply insets for.
 *//*from   w w w . j a  v  a2 s .  c  om*/
public static void applyTopWindowInsetsForView(@NonNull final View view) {
    view.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
        @Override
        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
            v.setPadding(v.getPaddingLeft(), insets.getSystemWindowInsetTop() + v.getPaddingTop(),
                    v.getPaddingRight(), v.getPaddingBottom());
            return insets;
        }
    });
    view.requestApplyInsets();
}

From source file:com.facebook.react.modules.statusbar.StatusBarModule.java

@ReactMethod
public void setTranslucent(final boolean translucent, final Promise res) {
    final Activity activity = getCurrentActivity();
    if (activity == null) {
        res.reject(ERROR_NO_ACTIVITY, ERROR_NO_ACTIVITY_MESSAGE);
        return;/*from ww w .java  2 s  .co m*/
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        UiThreadUtil.runOnUiThread(new Runnable() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void run() {
                // If the status bar is translucent hook into the window insets calculations
                // and consume all the top insets so no padding will be added under the status bar.
                View decorView = activity.getWindow().getDecorView();
                if (translucent) {
                    decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                        @Override
                        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                            WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                            return defaultInsets.replaceSystemWindowInsets(
                                    defaultInsets.getSystemWindowInsetLeft(), 0,
                                    defaultInsets.getSystemWindowInsetRight(),
                                    defaultInsets.getSystemWindowInsetBottom());
                        }
                    });
                } else {
                    decorView.setOnApplyWindowInsetsListener(null);
                }

                ViewCompat.requestApplyInsets(decorView);
                res.resolve(null);
            }
        });
    }
}

From source file:fr.outadev.skinswitch.DetailActivity.java

@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
private void applySystemWindowsBottomInset() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
        View containerView = findViewById(R.id.container);
        containerView.setFitsSystemWindows(true);

        containerView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {

            @Override//from w ww.  ja v  a2  s  .  co  m
            public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) {
                DisplayMetrics metrics = getResources().getDisplayMetrics();

                if (metrics.widthPixels < metrics.heightPixels) {
                    view.setPadding(0, 0, 0, windowInsets.getSystemWindowInsetBottom());
                } else {
                    view.setPadding(0, 0, windowInsets.getSystemWindowInsetRight(), 0);
                }

                return windowInsets.consumeSystemWindowInsets();
            }

        });
    }
}

From source file:meizhi.meizhi.malin.utils.DestroyCleanUtil.java

@SuppressLint("ObsoleteSdkInt")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static void unBindView(View view) {
    if (view == null)
        return;//from w  w  w .  j  a  v a 2  s.c o m
    Drawable drawable;
    int i;
    //1.
    try {
        view.setOnClickListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //2.
    try {
        view.setOnCreateContextMenuListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //3.
    try {
        view.setOnFocusChangeListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //4.
    try {
        view.setOnKeyListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //5.
    try {
        view.setOnLongClickListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //6.
    try {
        view.setOnTouchListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //7.
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            view.setOnApplyWindowInsetsListener(null);
        }
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //8.
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            view.setOnContextClickListener(null);
        }
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //9.
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            view.setOnScrollChangeListener(null);
        }
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //10.
    try {
        view.setOnDragListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //11.
    try {
        view.setOnGenericMotionListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //12.
    try {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB_MR2) {//13
            view.setOnHoverListener(null);
        }
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    //13.
    try {
        view.setOnSystemUiVisibilityChangeListener(null);
    } catch (Throwable e) {
        CrashReport.postCatchedException(e);
    }

    /**
     * @see SwipeRefreshLayout#onDetachedFromWindow()
     */
    if (view.getBackground() != null && !view.getClass().getName().equals(CIRCLE_CLASS)) {
        try {
            view.getBackground().setCallback(null);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {//16
                view.setBackgroundDrawable(null);
            } else {
                view.setBackground(null);
            }
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //ImageView
    if (view instanceof ImageView) {
        try {
            ImageView imageView = (ImageView) view;
            drawable = imageView.getDrawable();
            if (drawable != null) {
                drawable.setCallback(null);
            }
            imageView.setImageDrawable(null);
            imageView.setImageBitmap(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //TextView
    if (view instanceof TextView) {
        try {
            TextView textView = (TextView) view;
            textView.setCompoundDrawables(null, null, null, null);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                textView.setCompoundDrawablesRelative(null, null, null, null);
            }
            textView.setCursorVisible(false);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //ImageButton
    if (view instanceof ImageButton) {
        try {
            ImageButton imageButton = (ImageButton) view;
            drawable = imageButton.getDrawable();
            if (drawable != null) {
                drawable.setCallback(null);
            }
            imageButton.setImageDrawable(null);
            imageButton.setImageBitmap(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //ListView
    if (view instanceof ListView) {
        ListView listView = (ListView) view;

        try {
            listView.setAdapter(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        try {
            listView.setOnScrollListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        try {
            listView.setOnItemClickListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        try {
            listView.setOnItemLongClickListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }

        try {
            listView.setOnItemSelectedListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //RecyclerView
    if (view instanceof RecyclerView) {
        try {
            RecyclerView recyclerView = (RecyclerView) view;
            recyclerView.setAdapter(null);
            recyclerView.setChildDrawingOrderCallback(null);
            recyclerView.setOnScrollListener(null);
            recyclerView.addOnScrollListener(null);
            recyclerView.removeOnScrollListener(null);
            recyclerView.setRecyclerListener(null);
        } catch (Throwable e) {
            CrashReport.postCatchedException(e);
        }
    }

    //WebView
    if (view instanceof WebView) {

        WebView webView = (WebView) view;
        try {
            webView.stopLoading();
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            webView.removeAllViews();
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            webView.setWebChromeClient(null);
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            webView.setWebViewClient(null);
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            webView.destroy();
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

        try {
            if (null != view.getParent() && view.getParent() instanceof ViewGroup) {
                ((ViewGroup) view.getParent()).removeView(view);
            }
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }

    }

    //SurfaceView
    if (view instanceof SurfaceView) {
        try {
            SurfaceView surfaceView = (SurfaceView) view;
            SurfaceHolder holder = surfaceView.getHolder();
            if (holder != null) {
                Surface surface = holder.getSurface();
                if (surface != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        surface.release();
                    }
                }
            }
        } catch (Throwable ignored) {
            CrashReport.postCatchedException(ignored);
        }
    }

    view.destroyDrawingCache();
    view.clearAnimation();

    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        int childCount = (viewGroup).getChildCount();
        for (i = 0; i < childCount; i++) {
            unBindView((viewGroup).getChildAt(i));
        }
    }
}

From source file:com.facebook.react.views.webview.ReactWebViewManager.java

@Override
protected WebView createViewInstance(final ThemedReactContext reactContext) {
    final ReactWebView webView = new ReactWebView(reactContext);

    /**//from  ww w .  java  2 s  .c o m
     * cookie?
     * 5.0???cookie,5.0?false
     * 
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
    }

    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            reactContext.getCurrentActivity().startActivity(intent);

            //                DownloadManager.Request request = new DownloadManager.Request(
            //                        Uri.parse(url));
            //
            //                request.setMimeType(mimetype);
            //                String cookies = CookieManager.getInstance().getCookie(url);
            //                request.addRequestHeader("cookie", cookies);
            //                request.addRequestHeader("User-Agent", userAgent);
            //                request.allowScanningByMediaScanner();
            ////                request.setTitle()
            //                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            //                request.setDestinationInExternalPublicDir(
            //                        Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
            //                                url, contentDisposition, mimetype));
            //                DownloadManager dm = (DownloadManager) reactContext.getCurrentActivity().getSystemService(DOWNLOAD_SERVICE);
            //                dm.enqueue(request);
            //                Toast.makeText(reactContext, "...", //To notify the Client that the file is being downloaded
            //                        Toast.LENGTH_LONG).show();

        }
    });
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage message) {
            if (ReactBuildConfig.DEBUG) {
                return super.onConsoleMessage(message);
            }
            // Ignore console logs in non debug builds.
            return true;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File imageFile = new File(storageDir, /* directory */
                    imageFileName + ".jpg" /* filename */
            );
            return imageFile;
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent
                    .resolveActivity(reactContext.getCurrentActivity().getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    FLog.e(ReactConstants.TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("*/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "?");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            // final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
            // galleryIntent.setType("image/*");
            // final Intent chooserIntent = Intent.createChooser(galleryIntent, "Choose File");
            // reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

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

            if (mVideoView != null) {
                callback.onCustomViewHidden();
                return;
            }

            // Store the view and it's callback for later, so we can dispose of them correctly
            mVideoView = view;
            mCustomViewCallback = callback;

            view.setBackgroundColor(Color.BLACK);
            getRootView().addView(view, FULLSCREEN_LAYOUT_PARAMS);
            webView.setVisibility(View.GONE);

            UiThreadUtil.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    // If the status bar is translucent hook into the window insets calculations
                    // and consume all the top insets so no padding will be added under the status bar.
                    View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
                    decorView.setOnApplyWindowInsetsListener(null);
                    ViewCompat.requestApplyInsets(decorView);
                }
            });

            reactContext.getCurrentActivity()
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        }

        @Override
        public void onHideCustomView() {
            if (mVideoView == null) {
                return;
            }

            mVideoView.setVisibility(View.GONE);
            getRootView().removeView(mVideoView);
            mVideoView = null;
            mCustomViewCallback.onCustomViewHidden();
            webView.setVisibility(View.VISIBLE);
            //                View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
            //                // Show Status Bar.
            //                int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
            //                decorView.setSystemUiVisibility(uiOptions);

            UiThreadUtil.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    // If the status bar is translucent hook into the window insets calculations
                    // and consume all the top insets so no padding will be added under the status bar.
                    View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
                    //                                decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                    //                                    @Override
                    //                                    public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    //                                        WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    //                                        return defaultInsets.replaceSystemWindowInsets(
                    //                                                defaultInsets.getSystemWindowInsetLeft(),
                    //                                                0,
                    //                                                defaultInsets.getSystemWindowInsetRight(),
                    //                                                defaultInsets.getSystemWindowInsetBottom());
                    //                                    }
                    //                                });
                    decorView.setOnApplyWindowInsetsListener(null);
                    ViewCompat.requestApplyInsets(decorView);
                }
            });

            reactContext.getCurrentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }

        private ViewGroup getRootView() {
            return ((ViewGroup) reactContext.getCurrentActivity().findViewById(android.R.id.content));
        }

    });

    reactContext.addLifecycleEventListener(webView);
    reactContext.addActivityEventListener(new ActivityEventListener() {
        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
                return;
            }
            Uri[] results = null;

            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = new Uri[] { Uri.parse(mCameraPhotoPath) };
                    }
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) {
                        results = new Uri[] { Uri.parse(dataString) };
                    }
                }
            }

            if (results == null) {
                mFilePathCallback.onReceiveValue(new Uri[] {});
            } else {
                mFilePathCallback.onReceiveValue(results);
            }
            mFilePathCallback = null;
            return;
        }

        @Override
        public void onNewIntent(Intent intent) {
        }
    });
    mWebViewConfig.configWebView(webView);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(false);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setDefaultFontSize(16);
    webView.getSettings().setTextZoom(100);
    // Fixes broken full-screen modals/galleries due to body height being 0.
    webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    return webView;
}