Example usage for android.support.v4.view OnApplyWindowInsetsListener OnApplyWindowInsetsListener

List of usage examples for android.support.v4.view OnApplyWindowInsetsListener OnApplyWindowInsetsListener

Introduction

In this page you can find the example usage for android.support.v4.view OnApplyWindowInsetsListener OnApplyWindowInsetsListener.

Prototype

OnApplyWindowInsetsListener

Source Link

Usage

From source file:com.rubengees.introduction.IntroductionActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getFieldsFromBundle();/*from  w w w.  j av a  2s  . c o  m*/
    applyStyle();

    super.onCreate(savedInstanceState);
    setContentView(R.layout.introduction_activity);

    configuration = IntroductionConfiguration.getInstance();

    findViews();
    initSlides();
    initManagers();
    initViews();

    if (savedInstanceState == null) {
        select(0);
        pager.setCurrentItem(rtlAwarePosition(0));
    } else {
        previousPagerPosition = savedInstanceState.getInt(STATE_PREVIOUS_PAGER_POSITION);

        select(previousPagerPosition);
    }

    //Workaround for fitsSystemWindows in a ViewPager
    ViewCompat.setOnApplyWindowInsetsListener(pager, new OnApplyWindowInsetsListener() {
        @Override
        public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
            WindowInsetsCompat newInsets = ViewCompat.onApplyWindowInsets(v, insets);

            if (newInsets.isConsumed()) {
                return newInsets;
            }

            boolean consumed = false;

            if (newInsets.isConsumed()) {
                consumed = true;
            }

            for (int i = 0; i < pager.getChildCount(); i++) {
                ViewCompat.dispatchApplyWindowInsets(pager.getChildAt(i), newInsets);

                if (newInsets.isConsumed()) {
                    consumed = true;
                }
            }

            return consumed ? newInsets.consumeSystemWindowInsets() : newInsets;
        }
    });
}

From source file:com.google.android.apps.muzei.MainFragment.java

@Override
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) {
    // Set up the action bar
    final View actionBarContainer = view.findViewById(R.id.action_bar_container);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        actionBarContainer.setBackground(ScrimUtil.makeCubicGradientScrimDrawable(0x44000000, 8, Gravity.TOP));
    }/*w w w . j a  va2 s  .  co  m*/
    final Toolbar toolbar = view.findViewById(R.id.toolbar);
    AppCompatActivity activity = (AppCompatActivity) getActivity();
    if (activity != null) {
        activity.setSupportActionBar(toolbar);
        activity.getSupportActionBar().setDisplayShowTitleEnabled(false);
    }

    // Set up the container for the child fragments
    final View container = view.findViewById(R.id.container);
    if (savedInstanceState == null) {
        FirebaseAnalytics.getInstance(getActivity()).setCurrentScreen(getActivity(), "ArtDetail",
                ArtDetailFragment.class.getSimpleName());
        getChildFragmentManager().beginTransaction().replace(R.id.container, new ArtDetailFragment()).commit();
    }

    // Set up the bottom nav
    final BottomNavigationView bottomNavigationView = view.findViewById(R.id.bottom_nav);
    bottomNavigationView
            .setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull final MenuItem item) {
                    if (getChildFragmentManager().isStateSaved()) {
                        // Can't navigate after the state is saved
                        return false;
                    }
                    switch (item.getItemId()) {
                    case R.id.main_art_details:
                        FirebaseAnalytics.getInstance(getContext()).setCurrentScreen(getActivity(), "ArtDetail",
                                ArtDetailFragment.class.getSimpleName());
                        getChildFragmentManager().beginTransaction()
                                .replace(R.id.container, new ArtDetailFragment())
                                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit();
                        return true;
                    case R.id.main_choose_source:
                        FirebaseAnalytics.getInstance(getContext()).setCurrentScreen(getActivity(),
                                "ChooseSource", ChooseSourceFragment.class.getSimpleName());
                        getChildFragmentManager().popBackStack("main",
                                FragmentManager.POP_BACK_STACK_INCLUSIVE);
                        getChildFragmentManager().beginTransaction()
                                .replace(R.id.container, new ChooseSourceFragment()).addToBackStack("main")
                                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit();
                        return true;
                    case R.id.main_effects:
                        FirebaseAnalytics.getInstance(getContext()).setCurrentScreen(getActivity(), "Effects",
                                EffectsFragment.class.getSimpleName());
                        getChildFragmentManager().popBackStack("main",
                                FragmentManager.POP_BACK_STACK_INCLUSIVE);
                        getChildFragmentManager().beginTransaction()
                                .replace(R.id.container, new EffectsFragment()).addToBackStack("main")
                                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit();
                        return true;
                    default:
                        return false;
                    }
                }
            });
    bottomNavigationView.setOnNavigationItemReselectedListener(
            new BottomNavigationView.OnNavigationItemReselectedListener() {
                @Override
                public void onNavigationItemReselected(@NonNull final MenuItem item) {
                    if (item.getItemId() == R.id.main_art_details) {
                        getActivity().getWindow().getDecorView()
                                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN
                                        | View.SYSTEM_UI_FLAG_IMMERSIVE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                    }
                }
            });

    // Send the correct window insets to each view
    ViewCompat.setOnApplyWindowInsetsListener(view, new OnApplyWindowInsetsListener() {
        @Override
        public WindowInsetsCompat onApplyWindowInsets(final View v, final WindowInsetsCompat insets) {
            // Ensure the action bar container gets the appropriate insets
            ViewCompat.dispatchApplyWindowInsets(actionBarContainer,
                    insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(),
                            insets.getSystemWindowInsetTop(), insets.getSystemWindowInsetRight(), 0));
            ViewCompat.dispatchApplyWindowInsets(container, insets.replaceSystemWindowInsets(
                    insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(), 0));
            ViewCompat.dispatchApplyWindowInsets(bottomNavigationView,
                    insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), 0,
                            insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom()));
            return insets;
        }
    });

    // Listen for visibility changes to know when to hide our views
    view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
        @Override
        public void onSystemUiVisibilityChange(int vis) {
            final boolean visible = (vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) == 0;

            actionBarContainer.setVisibility(View.VISIBLE);
            actionBarContainer.animate().alpha(visible ? 1f : 0f).setDuration(200)
                    .withEndAction(new Runnable() {
                        @Override
                        public void run() {
                            if (!visible) {
                                actionBarContainer.setVisibility(View.GONE);
                            }
                        }
                    });

            bottomNavigationView.setVisibility(View.VISIBLE);
            bottomNavigationView.animate().alpha(visible ? 1f : 0f).setDuration(200)
                    .withEndAction(new Runnable() {
                        @Override
                        public void run() {
                            if (!visible) {
                                bottomNavigationView.setVisibility(View.GONE);
                            }
                        }
                    });
        }
    });

}

From source file:com.google.android.apps.muzei.gallery.GallerySettingsActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery_activity);
    Toolbar appBar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(appBar);/*from www . ja  v a 2s. co  m*/

    getSupportLoaderManager().initLoader(0, null, this);

    bindService(new Intent(this, GalleryArtSource.class).setAction(GalleryArtSource.ACTION_BIND_GALLERY),
            mServiceConnection, BIND_AUTO_CREATE);

    mPlaceholderDrawable = new ColorDrawable(
            ContextCompat.getColor(this, R.color.gallery_chosen_photo_placeholder));

    mPhotoGridView = (RecyclerView) findViewById(R.id.photo_grid);
    DefaultItemAnimator itemAnimator = new DefaultItemAnimator();
    itemAnimator.setSupportsChangeAnimations(false);
    mPhotoGridView.setItemAnimator(itemAnimator);
    setupMultiSelect();

    final GridLayoutManager gridLayoutManager = new GridLayoutManager(GallerySettingsActivity.this, 1);
    mPhotoGridView.setLayoutManager(gridLayoutManager);

    final ViewTreeObserver vto = mPhotoGridView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int width = mPhotoGridView.getWidth() - mPhotoGridView.getPaddingStart()
                    - mPhotoGridView.getPaddingEnd();
            if (width <= 0) {
                return;
            }

            // Compute number of columns
            int maxItemWidth = getResources()
                    .getDimensionPixelSize(R.dimen.gallery_chosen_photo_grid_max_item_size);
            int numColumns = 1;
            while (true) {
                if (width / numColumns > maxItemWidth) {
                    ++numColumns;
                } else {
                    break;
                }
            }

            int spacing = getResources().getDimensionPixelSize(R.dimen.gallery_chosen_photo_grid_spacing);
            mItemSize = (width - spacing * (numColumns - 1)) / numColumns;

            // Complete setup
            gridLayoutManager.setSpanCount(numColumns);
            mChosenPhotosAdapter.setHasStableIds(true);
            mPhotoGridView.setAdapter(mChosenPhotosAdapter);

            mPhotoGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            tryUpdateSelection(false);
        }
    });

    ViewCompat.setOnApplyWindowInsetsListener(mPhotoGridView, new OnApplyWindowInsetsListener() {
        @Override
        public WindowInsetsCompat onApplyWindowInsets(final View v, final WindowInsetsCompat insets) {
            int gridSpacing = getResources().getDimensionPixelSize(R.dimen.gallery_chosen_photo_grid_spacing);
            ViewCompat.onApplyWindowInsets(v,
                    insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft() + gridSpacing,
                            gridSpacing, insets.getSystemWindowInsetRight() + gridSpacing,
                            insets.getSystemWindowInsetBottom() + insets.getSystemWindowInsetTop() + gridSpacing
                                    + getResources().getDimensionPixelSize(R.dimen.gallery_fab_space)));

            return insets;
        }
    });

    Button enableRandomImages = (Button) findViewById(R.id.gallery_enable_random);
    enableRandomImages.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            ActivityCompat.requestPermissions(GallerySettingsActivity.this,
                    new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, REQUEST_STORAGE_PERMISSION);
        }
    });
    Button permissionSettings = (Button) findViewById(R.id.gallery_edit_permission_settings);
    permissionSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View view) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    Uri.fromParts("package", getPackageName(), null));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    });
    mAddButton = findViewById(R.id.add_photos_button);
    mAddButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Use ACTION_OPEN_DOCUMENT by default for adding photos.
            // This allows us to use persistent URI permissions to access the underlying photos
            // meaning we don't need to use additional storage space and will pull in edits automatically
            // in addition to syncing deletions.
            // (There's a separate 'Import photos' option which uses ACTION_GET_CONTENT to support legacy apps)
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            startActivityForResult(intent, REQUEST_CHOOSE_PHOTOS);
        }
    });
}

From source file:com.maxwen.wallpaper.board.activities.WallpaperBoardActivity.java

public void initMainActivity(@Nullable Bundle savedInstanceState, boolean isLicenseCheckerEnabled,
        @NonNull byte[] salt, @NonNull String licenseKey, @NonNull String[] donationProductsId) {
    super.setTheme(Preferences.getPreferences(this).isDarkTheme() ? R.style.AppThemeDark : R.style.AppTheme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wallpaper_board);
    ButterKnife.bind(this);

    ViewHelper.resetNavigationBarTranslucent(this, getResources().getConfiguration().orientation);

    ColorHelper.setStatusBarIconColor(this);
    registerBroadcastReceiver();/*  ww w. j a v a 2 s . c  om*/

    SoftKeyboardHelper softKeyboardHelper = new SoftKeyboardHelper(this, findViewById(R.id.container));
    softKeyboardHelper.enable();

    mFragManager = getSupportFragmentManager();
    mLicenseKey = licenseKey;
    mDonationProductsId = donationProductsId;

    Toolbar toolbar = ButterKnife.findById(this, R.id.toolbar);
    toolbar.setTitle("");

    ViewHelper.setupToolbar(toolbar, true);
    setSupportActionBar(toolbar);

    mBottomNavigationView.setOnNavigationItemSelectedListener(
            new BottomNavigationViewNew.OnNavigationItemSelectedListener() {
                @Override
                public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                    int id = item.getItemId();
                    int newPosition = -1;
                    if (id == R.id.navigation_view_wallpapers) {
                        newPosition = 0;
                    }
                    if (id == R.id.navigation_view_favorites) {
                        newPosition = 2;
                    }
                    if (id == R.id.navigation_view_categories) {
                        newPosition = 1;
                    }
                    if (id == R.id.navigation_view_new) {
                        newPosition = 4;
                    }
                    if (newPosition != -1 && newPosition != mPosition) {
                        setMenuChecked(false);
                        mPosition = newPosition;
                        setFragment(getFragment(mPosition));
                        item.setChecked(true);
                        mToolbarTitle.setText(getToolbarTitle());
                        return true;
                    }
                    if (id == R.id.menu_filter) {
                        final PopupMenu popup = new PopupMenu(WallpaperBoardActivity.this,
                                ((ViewGroup) mBottomNavigationView.getChildAt(0)).getChildAt(2));
                        fileCategoryMenu(popup.getMenu());
                        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                            public boolean onMenuItemClick(MenuItem item) {
                                item.setChecked(!item.isChecked());
                                new Database(WallpaperBoardActivity.this).selectCategory(
                                        item.getItemId() - MENU_CATEGORY_START, item.isChecked());
                                filterWallpapers();
                                return true;
                            }
                        });
                        popup.show();
                        return false;
                    }
                    return false;
                }
            });

    initInAppBilling();

    mPosition = 0;
    if (savedInstanceState != null) {
        mPosition = savedInstanceState.getInt(Extras.EXTRA_POSITION, 0);
    }
    setMenuChecked(false);
    setFragment(getFragment(mPosition));
    MenuItem item = mBottomNavigationView.getMenu().findItem(mapPositionToMenuId());
    if (item != null) {
        item.setChecked(true);
    }
    mToolbarTitle.setText(getToolbarTitle());

    ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.coordinator),
            new OnApplyWindowInsetsListener() { // setContentView() must be fired already
                @Override
                public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                    mNavBarHeight = insets.getSystemWindowInsetBottom();
                    ViewHelper.resetViewBottomPadding(mBottomNavigationView, mNavBarHeight, true);
                    // need to call here since first fragment is created before this
                    WallpapersFragment fragment = (WallpapersFragment) mFragManager
                            .findFragmentByTag(Extras.TAG_WALLPAPERS);
                    if (fragment != null) {
                        fragment.resetViewBottomPadding();
                    }
                    return insets;
                }
            });
    if (Preferences.getPreferences(this).isFirstRun() && isLicenseCheckerEnabled) {
        LicenseHelper.getLicenseChecker(this).checkLicense(mLicenseKey, salt);
        return;
    }

    checkWallpapers();

    if (isLicenseCheckerEnabled && !Preferences.getPreferences(this).isLicensed()) {
        finish();
    }
}

From source file:de.mrapp.android.dialog.decorator.MaterialDialogDecorator.java

/**
 * Creates and returns a listener, which allows to observe when window insets are applied to the
 * root view of the view hierarchy, which is modified by the decorator.
 *
 * @return The listener, which has been created, as an instance of the type {@link
 * OnApplyWindowInsetsListener}/* w w w.j a  va 2 s .  c  om*/
 */
private OnApplyWindowInsetsListener createWindowInsetsListener() {
    return new OnApplyWindowInsetsListener() {

        @Override
        public WindowInsetsCompat onApplyWindowInsets(final View v, final WindowInsetsCompat insets) {
            windowInsets = insets.hasSystemWindowInsets()
                    ? new Rect(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(),
                            insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom())
                    : null;
            adaptLayoutParams();
            return insets;
        }

    };
}

From source file:android.support.v7.app.AppCompatDelegateImplV7.java

private void ensureSubDecor() {
    if (!mSubDecorInstalled) {
        final LayoutInflater inflater = LayoutInflater.from(mContext);

        if (!mWindowNoTitle) {
            if (mIsFloating) {
                // If we're floating, inflate the dialog title decor
                mSubDecor = (ViewGroup) inflater.inflate(R.layout.abc_dialog_title_material, null);
            } else if (mHasActionBar) {
                /**/*  w w w .  j ava2s  .com*/
                 * This needs some explanation. As we can not use the android:theme attribute
                 * pre-L, we emulate it by manually creating a LayoutInflater using a
                 * ContextThemeWrapper pointing to actionBarTheme.
                 */
                TypedValue outValue = new TypedValue();
                mContext.getTheme().resolveAttribute(R.attr.actionBarTheme, outValue, true);

                Context themedContext;
                if (outValue.resourceId != 0) {
                    themedContext = new ContextThemeWrapper(mContext, outValue.resourceId);
                } else {
                    themedContext = mContext;
                }

                // Now inflate the view using the themed context and set it as the content view
                mSubDecor = (ViewGroup) LayoutInflater.from(themedContext).inflate(R.layout.abc_screen_toolbar,
                        null);

                mDecorContentParent = (DecorContentParent) mSubDecor.findViewById(R.id.decor_content_parent);
                mDecorContentParent.setWindowCallback(getWindowCallback());

                /**
                 * Propagate features to DecorContentParent
                 */
                if (mOverlayActionBar) {
                    mDecorContentParent.initFeature(FEATURE_ACTION_BAR_OVERLAY);
                }
                if (mFeatureProgress) {
                    mDecorContentParent.initFeature(Window.FEATURE_PROGRESS);
                }
                if (mFeatureIndeterminateProgress) {
                    mDecorContentParent.initFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
                }
            }
        } else {
            if (mOverlayActionMode) {
                mSubDecor = (ViewGroup) inflater.inflate(R.layout.abc_screen_simple_overlay_action_mode, null);
            } else {
                mSubDecor = (ViewGroup) inflater.inflate(R.layout.abc_screen_simple, null);
            }

            if (Build.VERSION.SDK_INT >= 21) {
                // If we're running on L or above, we can rely on ViewCompat's
                // setOnApplyWindowInsetsListener
                ViewCompat.setOnApplyWindowInsetsListener(mSubDecor, new OnApplyWindowInsetsListener() {
                    @Override
                    public WindowInsetsCompat onApplyWindowInsets(View v, WindowInsetsCompat insets) {
                        final int top = insets.getSystemWindowInsetTop();
                        final int newTop = updateStatusGuard(top);

                        if (top != newTop) {
                            insets = insets.replaceSystemWindowInsets(insets.getSystemWindowInsetLeft(), newTop,
                                    insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
                        }

                        // Now apply the insets on our view
                        return ViewCompat.onApplyWindowInsets(v, insets);
                    }
                });
            } else {
                // Else, we need to use our own FitWindowsViewGroup handling
                ((FitWindowsViewGroup) mSubDecor)
                        .setOnFitSystemWindowsListener(new FitWindowsViewGroup.OnFitSystemWindowsListener() {
                            @Override
                            public void onFitSystemWindows(Rect insets) {
                                insets.top = updateStatusGuard(insets.top);
                            }
                        });
            }
        }

        if (mSubDecor == null) {
            throw new IllegalArgumentException("AppCompat does not support the current theme features");
        }

        if (mDecorContentParent == null) {
            mTitleView = (TextView) mSubDecor.findViewById(R.id.title);
        }

        // Make the decor optionally fit system windows, like the window's decor
        ViewUtils.makeOptionalFitsSystemWindows(mSubDecor);

        final ViewGroup decorContent = (ViewGroup) mWindow.findViewById(android.R.id.content);
        final ViewGroup abcContent = (ViewGroup) mSubDecor.findViewById(R.id.action_bar_activity_content);

        // There might be Views already added to the Window's content view so we need to
        // migrate them to our content view
        while (decorContent.getChildCount() > 0) {
            final View child = decorContent.getChildAt(0);
            decorContent.removeViewAt(0);
            abcContent.addView(child);
        }

        // Now set the Window's content view with the decor
        mWindow.setContentView(mSubDecor);

        // Change our content FrameLayout to use the android.R.id.content id.
        // Useful for fragments.
        decorContent.setId(View.NO_ID);
        abcContent.setId(android.R.id.content);

        // The decorContent may have a foreground drawable set (windowContentOverlay).
        // Remove this as we handle it ourselves
        if (decorContent instanceof FrameLayout) {
            ((FrameLayout) decorContent).setForeground(null);
        }

        // If a title was set before we installed the decor, propogate it now
        CharSequence title = getTitle();
        if (!TextUtils.isEmpty(title)) {
            onTitleChanged(title);
        }

        applyFixedSizeWindow();

        onSubDecorInstalled(mSubDecor);

        mSubDecorInstalled = true;

        // Invalidate if the panel menu hasn't been created before this.
        // Panel menu invalidation is deferred avoiding application onCreateOptionsMenu
        // being called in the middle of onCreate or similar.
        // A pending invalidation will typically be resolved before the posted message
        // would run normally in order to satisfy instance state restoration.
        PanelFeatureState st = getPanelState(FEATURE_OPTIONS_PANEL, false);
        if (!isDestroyed() && (st == null || st.menu == null)) {
            invalidatePanelMenu(FEATURE_ACTION_BAR);
        }
    }
}