Search in sources :

Example 11 with StateListAnimator

use of android.animation.StateListAnimator in project Telegram-FOSS by Telegram-FOSS-Team.

the class ThemePreviewActivity method createView.

@SuppressLint("Recycle")
@Override
public View createView(Context context) {
    hasOwnBackground = true;
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }
    page1 = new FrameLayout(context);
    ActionBarMenu menu = actionBar.createMenu();
    final ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

        @Override
        public void onSearchExpand() {
        }

        @Override
        public boolean canCollapseSearch() {
            return true;
        }

        @Override
        public void onSearchCollapse() {
        }

        @Override
        public void onTextChanged(EditText editText) {
        }
    });
    item.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
    actionBar.setBackButtonDrawable(new MenuDrawable());
    actionBar.setAddToContainer(false);
    actionBar.setTitle(LocaleController.getString("ThemePreview", R.string.ThemePreview));
    page1 = new FrameLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            setMeasuredDimension(widthSize, heightSize);
            measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int actionBarHeight = actionBar.getMeasuredHeight();
            if (actionBar.getVisibility() == VISIBLE) {
                heightSize -= actionBarHeight;
            }
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
            layoutParams.topMargin = actionBarHeight;
            listView.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
            measureChildWithMargins(floatingButton, widthMeasureSpec, 0, heightMeasureSpec, 0);
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == actionBar && parentLayout != null) {
                parentLayout.drawHeaderShadow(canvas, actionBar.getVisibility() == VISIBLE ? actionBar.getMeasuredHeight() : 0);
            }
            return result;
        }
    };
    page1.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    page1.addView(actionBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    listView = new RecyclerListView(context);
    listView.setVerticalScrollBarEnabled(true);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    listView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
    listView.setVerticalScrollbarPosition(LocaleController.isRTL ? RecyclerListView.SCROLLBAR_POSITION_LEFT : RecyclerListView.SCROLLBAR_POSITION_RIGHT);
    listView.setPadding(0, 0, 0, AndroidUtilities.dp(screenType != SCREEN_TYPE_PREVIEW ? 12 : 0));
    listView.setOnItemClickListener((view, position) -> {
    });
    page1.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    floatingButton = new ImageView(context);
    floatingButton.setScaleType(ImageView.ScaleType.CENTER);
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_chats_actionBackground), Theme.getColor(Theme.key_chats_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        drawable = combinedDrawable;
    }
    floatingButton.setBackgroundDrawable(drawable);
    floatingButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_actionIcon), PorterDuff.Mode.MULTIPLY));
    floatingButton.setImageResource(R.drawable.floating_pencil);
    if (Build.VERSION.SDK_INT >= 21) {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        floatingButton.setStateListAnimator(animator);
        floatingButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            }
        });
    }
    page1.addView(floatingButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM, LocaleController.isRTL ? 14 : 0, 0, LocaleController.isRTL ? 0 : 14, 14));
    dialogsAdapter = new DialogsAdapter(context);
    listView.setAdapter(dialogsAdapter);
    page2 = new FrameLayout(context) {

        private boolean ignoreLayout;

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            setMeasuredDimension(widthSize, heightSize);
            if (dropDownContainer != null) {
                ignoreLayout = true;
                if (!AndroidUtilities.isTablet()) {
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) dropDownContainer.getLayoutParams();
                    layoutParams.topMargin = (Build.VERSION.SDK_INT >= 21 ? AndroidUtilities.statusBarHeight : 0);
                    dropDownContainer.setLayoutParams(layoutParams);
                }
                if (!AndroidUtilities.isTablet() && ApplicationLoader.applicationContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    dropDown.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
                } else {
                    dropDown.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
                }
                ignoreLayout = false;
            }
            measureChildWithMargins(actionBar2, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int actionBarHeight = actionBar2.getMeasuredHeight();
            if (actionBar2.getVisibility() == VISIBLE) {
                heightSize -= actionBarHeight;
            }
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView2.getLayoutParams();
            layoutParams.topMargin = actionBarHeight;
            listView2.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - layoutParams.bottomMargin, MeasureSpec.EXACTLY));
            layoutParams = (FrameLayout.LayoutParams) backgroundImage.getLayoutParams();
            layoutParams.topMargin = actionBarHeight;
            backgroundImage.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
            if (bottomOverlayChat != null) {
                measureChildWithMargins(bottomOverlayChat, widthMeasureSpec, 0, heightMeasureSpec, 0);
            }
            for (int a = 0; a < patternLayout.length; a++) {
                if (patternLayout[a] != null) {
                    measureChildWithMargins(patternLayout[a], widthMeasureSpec, 0, heightMeasureSpec, 0);
                }
            }
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == actionBar2 && parentLayout != null) {
                parentLayout.drawHeaderShadow(canvas, actionBar2.getVisibility() == VISIBLE ? (int) (actionBar2.getMeasuredHeight() + actionBar2.getTranslationY()) : 0);
            }
            return result;
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    messagesAdapter = new MessagesAdapter(context);
    actionBar2 = createActionBar(context);
    if (AndroidUtilities.isTablet()) {
        actionBar2.setOccupyStatusBar(false);
    }
    actionBar2.setBackButtonDrawable(new BackDrawable(false));
    actionBar2.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (checkDiscard()) {
                    cancelThemeApply(false);
                }
            } else if (id >= 1 && id <= 3) {
                selectColorType(id);
            } else if (id == 4) {
                if (removeBackgroundOverride) {
                    Theme.resetCustomWallpaper(false);
                }
                File path = accent.getPathToWallpaper();
                if (path != null) {
                    path.delete();
                }
                accent.patternSlug = selectedPattern != null ? selectedPattern.slug : "";
                accent.patternIntensity = currentIntensity;
                accent.patternMotion = isMotion;
                if ((int) accent.backgroundOverrideColor == 0) {
                    accent.backgroundOverrideColor = 0x100000000L;
                }
                if ((int) accent.backgroundGradientOverrideColor1 == 0) {
                    accent.backgroundGradientOverrideColor1 = 0x100000000L;
                }
                if ((int) accent.backgroundGradientOverrideColor2 == 0) {
                    accent.backgroundGradientOverrideColor2 = 0x100000000L;
                }
                if ((int) accent.backgroundGradientOverrideColor3 == 0) {
                    accent.backgroundGradientOverrideColor3 = 0x100000000L;
                }
                saveAccentWallpaper();
                NotificationCenter.getGlobalInstance().removeObserver(ThemePreviewActivity.this, NotificationCenter.wallpapersDidLoad);
                Theme.saveThemeAccents(applyingTheme, true, false, false, true);
                Theme.applyPreviousTheme();
                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, applyingTheme, nightTheme, null, -1);
                finishFragment();
            } else if (id == 5) {
                if (getParentActivity() == null) {
                    return;
                }
                String link;
                StringBuilder modes = new StringBuilder();
                if (isBlurred) {
                    modes.append("blur");
                }
                if (isMotion) {
                    if (modes.length() > 0) {
                        modes.append("+");
                    }
                    modes.append("motion");
                }
                if (currentWallpaper instanceof TLRPC.TL_wallPaper) {
                    TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) currentWallpaper;
                    link = "https://" + MessagesController.getInstance(currentAccount).linkPrefix + "/bg/" + wallPaper.slug;
                    if (modes.length() > 0) {
                        link += "?mode=" + modes.toString();
                    }
                } else if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
                    WallpapersListActivity.ColorWallpaper colorWallpaper = new WallpapersListActivity.ColorWallpaper(selectedPattern != null ? selectedPattern.slug : Theme.COLOR_BACKGROUND_SLUG, backgroundColor, backgroundGradientColor1, backgroundGradientColor2, backgroundGradientColor3, backgroundRotation, currentIntensity, isMotion, null);
                    colorWallpaper.pattern = selectedPattern;
                    link = colorWallpaper.getUrl();
                } else {
                    if (BuildVars.DEBUG_PRIVATE_VERSION) {
                        Theme.ThemeAccent accent = Theme.getActiveTheme().getAccent(false);
                        if (accent != null) {
                            WallpapersListActivity.ColorWallpaper colorWallpaper = new WallpapersListActivity.ColorWallpaper(accent.patternSlug, (int) accent.backgroundOverrideColor, (int) accent.backgroundGradientOverrideColor1, (int) accent.backgroundGradientOverrideColor2, (int) accent.backgroundGradientOverrideColor3, accent.backgroundRotation, accent.patternIntensity, accent.patternMotion, null);
                            for (int a = 0, N = patterns.size(); a < N; a++) {
                                TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) patterns.get(a);
                                if (wallPaper.pattern) {
                                    if (accent.patternSlug.equals(wallPaper.slug)) {
                                        colorWallpaper.pattern = wallPaper;
                                        break;
                                    }
                                }
                            }
                            link = colorWallpaper.getUrl();
                        } else {
                            return;
                        }
                    } else {
                        return;
                    }
                }
                showDialog(new ShareAlert(getParentActivity(), null, link, false, link, false) {

                    @Override
                    protected void onSend(LongSparseArray<TLRPC.Dialog> dids, int count) {
                        if (dids.size() == 1) {
                            undoView.showWithAction(dids.valueAt(0).id, UndoView.ACTION_SHARE_BACKGROUND, count);
                        } else {
                            undoView.showWithAction(0, UndoView.ACTION_SHARE_BACKGROUND, count, dids.size(), null, null);
                        }
                    }
                });
            }
        }
    });
    backgroundImage = new BackupImageView(context) {

        private Drawable background;

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            parallaxScale = parallaxEffect.getScale(getMeasuredWidth(), getMeasuredHeight());
            if (isMotion) {
                setScaleX(parallaxScale);
                setScaleY(parallaxScale);
            }
            if (radialProgress != null) {
                int size = AndroidUtilities.dp(44);
                int x = (getMeasuredWidth() - size) / 2;
                int y = (getMeasuredHeight() - size) / 2;
                radialProgress.setProgressRect(x, y, x + size, y + size);
            }
            progressVisible = screenType == SCREEN_TYPE_CHANGE_BACKGROUND && getMeasuredWidth() <= getMeasuredHeight();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (background instanceof ColorDrawable || background instanceof GradientDrawable || background instanceof MotionBackgroundDrawable) {
                background.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
                background.draw(canvas);
            } else if (background instanceof BitmapDrawable) {
                BitmapDrawable bitmapDrawable = (BitmapDrawable) background;
                if (bitmapDrawable.getTileModeX() == Shader.TileMode.REPEAT) {
                    canvas.save();
                    float scale = 2.0f / AndroidUtilities.density;
                    canvas.scale(scale, scale);
                    background.setBounds(0, 0, (int) Math.ceil(getMeasuredWidth() / scale), (int) Math.ceil(getMeasuredHeight() / scale));
                    background.draw(canvas);
                    canvas.restore();
                } else {
                    int viewHeight = getMeasuredHeight();
                    float scaleX = (float) getMeasuredWidth() / (float) background.getIntrinsicWidth();
                    float scaleY = (float) (viewHeight) / (float) background.getIntrinsicHeight();
                    float scale = Math.max(scaleX, scaleY);
                    int width = (int) Math.ceil(background.getIntrinsicWidth() * scale * parallaxScale);
                    int height = (int) Math.ceil(background.getIntrinsicHeight() * scale * parallaxScale);
                    int x = (getMeasuredWidth() - width) / 2;
                    int y = (viewHeight - height) / 2;
                    background.setBounds(x, y, x + width, y + height);
                    background.draw(canvas);
                }
            }
            super.onDraw(canvas);
            if (progressVisible && radialProgress != null) {
                radialProgress.draw(canvas);
            }
        }

        @Override
        public Drawable getBackground() {
            return background;
        }

        @Override
        public void setBackground(Drawable drawable) {
            background = drawable;
        }

        @Override
        public void setAlpha(float alpha) {
            if (radialProgress != null) {
                radialProgress.setOverrideAlpha(alpha);
            }
        }
    };
    page2.addView(backgroundImage, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 48));
    if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
        backgroundImage.getImageReceiver().setDelegate((imageReceiver, set, thumb, memCache) -> {
            if (!(currentWallpaper instanceof WallpapersListActivity.ColorWallpaper)) {
                Drawable dr = imageReceiver.getDrawable();
                if (set && dr != null) {
                    if (!Theme.hasThemeKey(Theme.key_chat_serviceBackground) || backgroundImage.getBackground() instanceof MotionBackgroundDrawable) {
                        Theme.applyChatServiceMessageColor(AndroidUtilities.calcDrawableColor(dr), dr);
                    }
                    listView2.invalidateViews();
                    if (backgroundButtonsContainer != null) {
                        for (int a = 0, N = backgroundButtonsContainer.getChildCount(); a < N; a++) {
                            backgroundButtonsContainer.getChildAt(a).invalidate();
                        }
                    }
                    if (messagesButtonsContainer != null) {
                        for (int a = 0, N = messagesButtonsContainer.getChildCount(); a < N; a++) {
                            messagesButtonsContainer.getChildAt(a).invalidate();
                        }
                    }
                    if (radialProgress != null) {
                        radialProgress.setColors(Theme.key_chat_serviceBackground, Theme.key_chat_serviceBackground, Theme.key_chat_serviceText, Theme.key_chat_serviceText);
                    }
                    if (!thumb && isBlurred && blurredBitmap == null) {
                        backgroundImage.getImageReceiver().setCrossfadeWithOldImage(false);
                        updateBlurred();
                        backgroundImage.getImageReceiver().setCrossfadeWithOldImage(true);
                    }
                }
            }
        });
    }
    if (messagesAdapter.showSecretMessages) {
        actionBar2.setTitle("Telegram Beta Chat");
        actionBar2.setSubtitle(LocaleController.formatPluralString("Members", 505));
    } else {
        if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
            actionBar2.setTitle(LocaleController.getString("BackgroundPreview", R.string.BackgroundPreview));
            if (BuildVars.DEBUG_PRIVATE_VERSION && Theme.getActiveTheme().getAccent(false) != null || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper && !Theme.DEFAULT_BACKGROUND_SLUG.equals(((WallpapersListActivity.ColorWallpaper) currentWallpaper).slug) || currentWallpaper instanceof TLRPC.TL_wallPaper) {
                ActionBarMenu menu2 = actionBar2.createMenu();
                menu2.addItem(5, R.drawable.msg_share_filled);
            }
        } else if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
            ActionBarMenu menu2 = actionBar2.createMenu();
            saveItem = menu2.addItem(4, LocaleController.getString("Save", R.string.Save).toUpperCase());
            dropDownContainer = new ActionBarMenuItem(context, menu2, 0, 0) {

                @Override
                public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
                    super.onInitializeAccessibilityNodeInfo(info);
                    info.setText(dropDown.getText());
                }
            };
            dropDownContainer.setSubMenuOpenSide(1);
            dropDownContainer.addSubItem(2, LocaleController.getString("ColorPickerBackground", R.string.ColorPickerBackground));
            dropDownContainer.addSubItem(1, LocaleController.getString("ColorPickerMainColor", R.string.ColorPickerMainColor));
            dropDownContainer.addSubItem(3, LocaleController.getString("ColorPickerMyMessages", R.string.ColorPickerMyMessages));
            dropDownContainer.setAllowCloseAnimation(false);
            dropDownContainer.setForceSmoothKeyboard(true);
            actionBar2.addView(dropDownContainer, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 64 : 56, 0, 40, 0));
            dropDownContainer.setOnClickListener(view -> dropDownContainer.toggleSubMenu());
            dropDown = new TextView(context);
            dropDown.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
            dropDown.setGravity(Gravity.LEFT);
            dropDown.setSingleLine(true);
            dropDown.setLines(1);
            dropDown.setMaxLines(1);
            dropDown.setEllipsize(TextUtils.TruncateAt.END);
            dropDown.setTextColor(Theme.getColor(Theme.key_actionBarDefaultTitle));
            dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            dropDown.setText(LocaleController.getString("ColorPickerMainColor", R.string.ColorPickerMainColor));
            Drawable dropDownDrawable = context.getResources().getDrawable(R.drawable.ic_arrow_drop_down).mutate();
            dropDownDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_actionBarDefaultTitle), PorterDuff.Mode.MULTIPLY));
            dropDown.setCompoundDrawablesWithIntrinsicBounds(null, null, dropDownDrawable, null);
            dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4));
            dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0);
            dropDownContainer.addView(dropDown, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 16, 0, 0, 1));
        } else {
            String name = applyingTheme.info != null ? applyingTheme.info.title : applyingTheme.getName();
            int index = name.lastIndexOf(".attheme");
            if (index >= 0) {
                name = name.substring(0, index);
            }
            actionBar2.setTitle(name);
            if (applyingTheme.info != null && applyingTheme.info.installs_count > 0) {
                actionBar2.setSubtitle(LocaleController.formatPluralString("ThemeInstallCount", applyingTheme.info.installs_count));
            } else {
                actionBar2.setSubtitle(LocaleController.formatDateOnline(System.currentTimeMillis() / 1000 - 60 * 60));
            }
        }
    }
    listView2 = new RecyclerListView(context) {

        @Override
        public boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child instanceof ChatMessageCell) {
                ChatMessageCell chatMessageCell = (ChatMessageCell) child;
                MessageObject message = chatMessageCell.getMessageObject();
                ImageReceiver imageReceiver = chatMessageCell.getAvatarImage();
                if (imageReceiver != null) {
                    int top = child.getTop();
                    if (chatMessageCell.isPinnedBottom()) {
                        ViewHolder holder = listView2.getChildViewHolder(child);
                        if (holder != null) {
                            int p = holder.getAdapterPosition();
                            int nextPosition;
                            nextPosition = p - 1;
                            holder = listView2.findViewHolderForAdapterPosition(nextPosition);
                            if (holder != null) {
                                imageReceiver.setImageY(-AndroidUtilities.dp(1000));
                                imageReceiver.draw(canvas);
                                return result;
                            }
                        }
                    }
                    float tx = chatMessageCell.getTranslationX();
                    int y = child.getTop() + chatMessageCell.getLayoutHeight();
                    int maxY = listView2.getMeasuredHeight() - listView2.getPaddingBottom();
                    if (y > maxY) {
                        y = maxY;
                    }
                    if (chatMessageCell.isPinnedTop()) {
                        ViewHolder holder = listView2.getChildViewHolder(child);
                        if (holder != null) {
                            int tries = 0;
                            while (true) {
                                if (tries >= 20) {
                                    break;
                                }
                                tries++;
                                int p = holder.getAdapterPosition();
                                int prevPosition = p + 1;
                                holder = listView2.findViewHolderForAdapterPosition(prevPosition);
                                if (holder != null) {
                                    top = holder.itemView.getTop();
                                    if (y - AndroidUtilities.dp(48) < holder.itemView.getBottom()) {
                                        tx = Math.min(holder.itemView.getTranslationX(), tx);
                                    }
                                    if (holder.itemView instanceof ChatMessageCell) {
                                        ChatMessageCell cell = (ChatMessageCell) holder.itemView;
                                        if (!cell.isPinnedTop()) {
                                            break;
                                        }
                                    } else {
                                        break;
                                    }
                                } else {
                                    break;
                                }
                            }
                        }
                    }
                    if (y - AndroidUtilities.dp(48) < top) {
                        y = top + AndroidUtilities.dp(48);
                    }
                    if (tx != 0) {
                        canvas.save();
                        canvas.translate(tx, 0);
                    }
                    imageReceiver.setImageY(y - AndroidUtilities.dp(44));
                    imageReceiver.draw(canvas);
                    if (tx != 0) {
                        canvas.restore();
                    }
                }
            }
            return result;
        }

        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            if (backgroundCheckBoxView != null) {
                for (int a = 0; a < backgroundCheckBoxView.length; a++) {
                    backgroundCheckBoxView[a].invalidate();
                }
            }
            if (messagesCheckBoxView != null) {
                for (int a = 0; a < messagesCheckBoxView.length; a++) {
                    messagesCheckBoxView[a].invalidate();
                }
            }
            if (backgroundPlayAnimationView != null) {
                backgroundPlayAnimationView.invalidate();
            }
            if (messagesPlayAnimationView != null) {
                messagesPlayAnimationView.invalidate();
            }
        }

        @Override
        protected void onChildPressed(View child, float x, float y, boolean pressed) {
            if (pressed && child instanceof ChatMessageCell) {
                ChatMessageCell messageCell = (ChatMessageCell) child;
                if (!messageCell.isInsideBackground(x, y)) {
                    return;
                }
            }
            super.onChildPressed(child, x, y, pressed);
        }

        @Override
        protected boolean allowSelectChildAtPosition(View child) {
            RecyclerView.ViewHolder holder = listView2.findContainingViewHolder(child);
            if (holder != null && holder.getItemViewType() == 2) {
                return false;
            }
            return super.allowSelectChildAtPosition(child);
        }

        @Override
        public boolean onTouchEvent(MotionEvent e) {
            checkMotionEvent(e);
            return super.onTouchEvent(e);
        }

        private void checkMotionEvent(MotionEvent e) {
            if (e.getAction() == MotionEvent.ACTION_UP) {
                if (!wasScroll && currentWallpaper instanceof WallpapersListActivity.ColorWallpaper && patternLayout[0].getVisibility() == View.VISIBLE) {
                    showPatternsView(0, false, true);
                }
                wasScroll = false;
            }
        }
    };
    DefaultItemAnimator itemAnimator = new DefaultItemAnimator() {

        @Override
        protected void onMoveAnimationUpdate(RecyclerView.ViewHolder holder) {
            listView2.invalidateViews();
        }
    };
    itemAnimator.setDelayAnimations(false);
    listView2.setItemAnimator(itemAnimator);
    listView2.setVerticalScrollBarEnabled(true);
    listView2.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
        listView2.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4 + 48));
    } else if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
        listView2.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(16));
    } else {
        listView2.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4));
    }
    listView2.setClipToPadding(false);
    listView2.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true));
    listView2.setVerticalScrollbarPosition(LocaleController.isRTL ? RecyclerListView.SCROLLBAR_POSITION_LEFT : RecyclerListView.SCROLLBAR_POSITION_RIGHT);
    if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
        page2.addView(listView2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, 273));
        listView2.setOnItemClickListener((view, position, x, y) -> {
            if (view instanceof ChatMessageCell) {
                ChatMessageCell cell = (ChatMessageCell) view;
                if (cell.isInsideBackground(x, y)) {
                    if (cell.getMessageObject().isOutOwner()) {
                        selectColorType(3);
                    } else {
                        selectColorType(1);
                    }
                } else {
                    selectColorType(2);
                }
            }
        });
    } else {
        page2.addView(listView2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    }
    listView2.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            listView2.invalidateViews();
            wasScroll = true;
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                wasScroll = false;
            }
        }
    });
    page2.addView(actionBar2, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    parallaxEffect = new WallpaperParallaxEffect(context);
    parallaxEffect.setCallback((offsetX, offsetY, angle) -> {
        if (!isMotion) {
            return;
        }
        Drawable background = backgroundImage.getBackground();
        float progress;
        if (motionAnimation != null) {
            progress = (backgroundImage.getScaleX() - 1.0f) / (parallaxScale - 1.0f);
        } else {
            progress = 1.0f;
        }
        backgroundImage.setTranslationX(offsetX * progress);
        backgroundImage.setTranslationY(offsetY * progress);
    });
    if (screenType == SCREEN_TYPE_ACCENT_COLOR || screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
        radialProgress = new RadialProgress2(backgroundImage);
        radialProgress.setColors(Theme.key_chat_serviceBackground, Theme.key_chat_serviceBackground, Theme.key_chat_serviceText, Theme.key_chat_serviceText);
        if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
            bottomOverlayChat = new FrameLayout(context) {

                @Override
                public void onDraw(Canvas canvas) {
                    int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
                    Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
                    Theme.chat_composeShadowDrawable.draw(canvas);
                    canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint);
                }
            };
            bottomOverlayChat.setWillNotDraw(false);
            bottomOverlayChat.setPadding(0, AndroidUtilities.dp(3), 0, 0);
            page2.addView(bottomOverlayChat, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
            bottomOverlayChat.setOnClickListener(view -> {
                boolean done;
                boolean sameFile = false;
                Theme.ThemeInfo theme = Theme.getActiveTheme();
                String originalFileName = theme.generateWallpaperName(null, isBlurred);
                String fileName = isBlurred ? theme.generateWallpaperName(null, false) : originalFileName;
                File toFile = new File(ApplicationLoader.getFilesDirFixed(), originalFileName);
                if (currentWallpaper instanceof TLRPC.TL_wallPaper) {
                    if (originalBitmap != null) {
                        try {
                            FileOutputStream stream = new FileOutputStream(toFile);
                            originalBitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
                            stream.close();
                            done = true;
                        } catch (Exception e) {
                            done = false;
                            FileLog.e(e);
                        }
                    } else {
                        ImageReceiver imageReceiver = backgroundImage.getImageReceiver();
                        if (imageReceiver.hasNotThumb() || imageReceiver.hasStaticThumb()) {
                            Bitmap bitmap = imageReceiver.getBitmap();
                            try {
                                FileOutputStream stream = new FileOutputStream(toFile);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
                                stream.close();
                                done = true;
                            } catch (Exception e) {
                                done = false;
                                FileLog.e(e);
                            }
                        } else {
                            done = false;
                        }
                    }
                    if (!done) {
                        TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) currentWallpaper;
                        File f = FileLoader.getPathToAttach(wallPaper.document, true);
                        try {
                            done = AndroidUtilities.copyFile(f, toFile);
                        } catch (Exception e) {
                            done = false;
                            FileLog.e(e);
                        }
                    }
                } else if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
                    if (selectedPattern != null) {
                        try {
                            WallpapersListActivity.ColorWallpaper wallPaper = (WallpapersListActivity.ColorWallpaper) currentWallpaper;
                            Bitmap bitmap = backgroundImage.getImageReceiver().getBitmap();
                            @SuppressLint("DrawAllocation") Bitmap dst = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
                            Canvas canvas = new Canvas(dst);
                            if (backgroundGradientColor2 != 0) {
                            } else if (backgroundGradientColor1 != 0) {
                                GradientDrawable gradientDrawable = new GradientDrawable(BackgroundGradientDrawable.getGradientOrientation(backgroundRotation), new int[] { backgroundColor, backgroundGradientColor1 });
                                gradientDrawable.setBounds(0, 0, dst.getWidth(), dst.getHeight());
                                gradientDrawable.draw(canvas);
                            } else {
                                canvas.drawColor(backgroundColor);
                            }
                            Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
                            paint.setColorFilter(new PorterDuffColorFilter(patternColor, blendMode));
                            paint.setAlpha((int) (255 * Math.abs(currentIntensity)));
                            canvas.drawBitmap(bitmap, 0, 0, paint);
                            FileOutputStream stream = new FileOutputStream(toFile);
                            if (backgroundGradientColor2 != 0) {
                                dst.compress(Bitmap.CompressFormat.PNG, 100, stream);
                            } else {
                                dst.compress(Bitmap.CompressFormat.JPEG, 87, stream);
                            }
                            stream.close();
                            done = true;
                        } catch (Throwable e) {
                            FileLog.e(e);
                            done = false;
                        }
                    } else {
                        done = true;
                    }
                } else if (currentWallpaper instanceof WallpapersListActivity.FileWallpaper) {
                    WallpapersListActivity.FileWallpaper wallpaper = (WallpapersListActivity.FileWallpaper) currentWallpaper;
                    if (wallpaper.resId != 0 || Theme.THEME_BACKGROUND_SLUG.equals(wallpaper.slug)) {
                        done = true;
                    } else {
                        try {
                            File fromFile = wallpaper.originalPath != null ? wallpaper.originalPath : wallpaper.path;
                            if (sameFile = fromFile.equals(toFile)) {
                                done = true;
                            } else {
                                done = AndroidUtilities.copyFile(fromFile, toFile);
                            }
                        } catch (Exception e) {
                            done = false;
                            FileLog.e(e);
                        }
                    }
                } else if (currentWallpaper instanceof MediaController.SearchImage) {
                    MediaController.SearchImage wallpaper = (MediaController.SearchImage) currentWallpaper;
                    File f;
                    if (wallpaper.photo != null) {
                        TLRPC.PhotoSize image = FileLoader.getClosestPhotoSizeWithSize(wallpaper.photo.sizes, maxWallpaperSize, true);
                        f = FileLoader.getPathToAttach(image, true);
                    } else {
                        f = ImageLoader.getHttpFilePath(wallpaper.imageUrl, "jpg");
                    }
                    try {
                        done = AndroidUtilities.copyFile(f, toFile);
                    } catch (Exception e) {
                        done = false;
                        FileLog.e(e);
                    }
                } else {
                    done = false;
                }
                if (isBlurred) {
                    try {
                        File blurredFile = new File(ApplicationLoader.getFilesDirFixed(), fileName);
                        FileOutputStream stream = new FileOutputStream(blurredFile);
                        blurredBitmap.compress(Bitmap.CompressFormat.JPEG, 87, stream);
                        stream.close();
                        done = true;
                    } catch (Throwable e) {
                        FileLog.e(e);
                        done = false;
                    }
                }
                String slug;
                int rotation = 45;
                int color = 0;
                int gradientColor1 = 0;
                int gradientColor2 = 0;
                int gradientColor3 = 0;
                File path = null;
                if (currentWallpaper instanceof TLRPC.TL_wallPaper) {
                    TLRPC.TL_wallPaper wallPaper = (TLRPC.TL_wallPaper) currentWallpaper;
                    slug = wallPaper.slug;
                } else if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
                    WallpapersListActivity.ColorWallpaper wallPaper = (WallpapersListActivity.ColorWallpaper) currentWallpaper;
                    if (Theme.DEFAULT_BACKGROUND_SLUG.equals(wallPaper.slug)) {
                        slug = Theme.DEFAULT_BACKGROUND_SLUG;
                        color = 0;
                    } else {
                        if (selectedPattern != null) {
                            slug = selectedPattern.slug;
                        } else {
                            slug = Theme.COLOR_BACKGROUND_SLUG;
                        }
                        color = backgroundColor;
                        gradientColor1 = backgroundGradientColor1;
                        gradientColor2 = backgroundGradientColor2;
                        gradientColor3 = backgroundGradientColor3;
                        rotation = backgroundRotation;
                    }
                } else if (currentWallpaper instanceof WallpapersListActivity.FileWallpaper) {
                    WallpapersListActivity.FileWallpaper wallPaper = (WallpapersListActivity.FileWallpaper) currentWallpaper;
                    slug = wallPaper.slug;
                    path = wallPaper.path;
                } else if (currentWallpaper instanceof MediaController.SearchImage) {
                    MediaController.SearchImage wallPaper = (MediaController.SearchImage) currentWallpaper;
                    if (wallPaper.photo != null) {
                        TLRPC.PhotoSize image = FileLoader.getClosestPhotoSizeWithSize(wallPaper.photo.sizes, maxWallpaperSize, true);
                        path = FileLoader.getPathToAttach(image, true);
                    } else {
                        path = ImageLoader.getHttpFilePath(wallPaper.imageUrl, "jpg");
                    }
                    slug = "";
                } else {
                    color = 0;
                    slug = Theme.DEFAULT_BACKGROUND_SLUG;
                }
                Theme.OverrideWallpaperInfo wallpaperInfo = new Theme.OverrideWallpaperInfo();
                wallpaperInfo.fileName = fileName;
                wallpaperInfo.originalFileName = originalFileName;
                wallpaperInfo.slug = slug;
                wallpaperInfo.isBlurred = isBlurred;
                wallpaperInfo.isMotion = isMotion;
                wallpaperInfo.color = color;
                wallpaperInfo.gradientColor1 = gradientColor1;
                wallpaperInfo.gradientColor2 = gradientColor2;
                wallpaperInfo.gradientColor3 = gradientColor3;
                wallpaperInfo.rotation = rotation;
                wallpaperInfo.intensity = currentIntensity;
                if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
                    WallpapersListActivity.ColorWallpaper colorWallpaper = (WallpapersListActivity.ColorWallpaper) currentWallpaper;
                    String slugStr;
                    if (!Theme.COLOR_BACKGROUND_SLUG.equals(slug) && !Theme.THEME_BACKGROUND_SLUG.equals(slug) && !Theme.DEFAULT_BACKGROUND_SLUG.equals(slug)) {
                        slugStr = slug;
                    } else {
                        slugStr = null;
                    }
                    float intensity = colorWallpaper.intensity;
                    if (intensity < 0 && !Theme.getActiveTheme().isDark()) {
                        intensity *= -1;
                    }
                    if (colorWallpaper.parentWallpaper != null && colorWallpaper.color == color && colorWallpaper.gradientColor1 == gradientColor1 && colorWallpaper.gradientColor2 == gradientColor2 && colorWallpaper.gradientColor3 == gradientColor3 && TextUtils.equals(colorWallpaper.slug, slugStr) && colorWallpaper.gradientRotation == rotation && (selectedPattern == null || Math.abs(intensity - currentIntensity) < 0.001f)) {
                        wallpaperInfo.wallpaperId = colorWallpaper.parentWallpaper.id;
                        wallpaperInfo.accessHash = colorWallpaper.parentWallpaper.access_hash;
                    }
                }
                MessagesController.getInstance(currentAccount).saveWallpaperToServer(path, wallpaperInfo, slug != null, 0);
                if (done) {
                    Theme.serviceMessageColorBackup = Theme.getColor(Theme.key_chat_serviceBackground);
                    if (Theme.THEME_BACKGROUND_SLUG.equals(wallpaperInfo.slug)) {
                        wallpaperInfo = null;
                    }
                    Theme.getActiveTheme().setOverrideWallpaper(wallpaperInfo);
                    Theme.reloadWallpaper();
                    if (!sameFile) {
                        ImageLoader.getInstance().removeImage(ImageLoader.getHttpFileName(toFile.getAbsolutePath()) + "@100_100");
                    }
                }
                if (delegate != null) {
                    delegate.didSetNewBackground();
                }
                finishFragment();
            });
            bottomOverlayChatText = new TextView(context);
            bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
            bottomOverlayChatText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            bottomOverlayChatText.setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText));
            bottomOverlayChatText.setText(LocaleController.getString("SetBackground", R.string.SetBackground));
            bottomOverlayChat.addView(bottomOverlayChatText, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        }
        Rect paddings = new Rect();
        sheetDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate();
        sheetDrawable.getPadding(paddings);
        sheetDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhite), PorterDuff.Mode.MULTIPLY));
        TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setTextSize(AndroidUtilities.dp(14));
        textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        {
            int textsCount;
            if (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
                textsCount = 3;
                if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper && Theme.DEFAULT_BACKGROUND_SLUG.equals(((WallpapersListActivity.ColorWallpaper) currentWallpaper).slug)) {
                    textsCount = 0;
                }
            } else {
                textsCount = 2;
                if (currentWallpaper instanceof WallpapersListActivity.FileWallpaper) {
                    WallpapersListActivity.FileWallpaper fileWallpaper = (WallpapersListActivity.FileWallpaper) currentWallpaper;
                    if (Theme.THEME_BACKGROUND_SLUG.equals(fileWallpaper.slug)) {
                        textsCount = 0;
                    }
                }
            }
            String[] texts = new String[textsCount];
            int[] textSizes = new int[textsCount];
            backgroundCheckBoxView = new WallpaperCheckBoxView[textsCount];
            int maxTextSize = 0;
            if (textsCount != 0) {
                backgroundButtonsContainer = new FrameLayout(context);
                if (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
                    texts[0] = LocaleController.getString("BackgroundColors", R.string.BackgroundColors);
                    texts[1] = LocaleController.getString("BackgroundPattern", R.string.BackgroundPattern);
                    texts[2] = LocaleController.getString("BackgroundMotion", R.string.BackgroundMotion);
                } else {
                    texts[0] = LocaleController.getString("BackgroundBlurred", R.string.BackgroundBlurred);
                    texts[1] = LocaleController.getString("BackgroundMotion", R.string.BackgroundMotion);
                }
                for (int a = 0; a < texts.length; a++) {
                    textSizes[a] = (int) Math.ceil(textPaint.measureText(texts[a]));
                    maxTextSize = Math.max(maxTextSize, textSizes[a]);
                }
                backgroundPlayAnimationView = new FrameLayout(context) {

                    private RectF rect = new RectF();

                    @Override
                    protected void onDraw(Canvas canvas) {
                        rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
                        Theme.applyServiceShaderMatrixForView(backgroundPlayAnimationView, backgroundImage);
                        canvas.drawRoundRect(rect, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Theme.chat_actionBackgroundPaint);
                        if (Theme.hasGradientService()) {
                            canvas.drawRoundRect(rect, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Theme.chat_actionBackgroundGradientDarkenPaint);
                        }
                    }
                };
                backgroundPlayAnimationView.setWillNotDraw(false);
                backgroundPlayAnimationView.setVisibility(backgroundGradientColor1 != 0 ? View.VISIBLE : View.INVISIBLE);
                backgroundPlayAnimationView.setScaleX(backgroundGradientColor1 != 0 ? 1.0f : 0.1f);
                backgroundPlayAnimationView.setScaleY(backgroundGradientColor1 != 0 ? 1.0f : 0.1f);
                backgroundPlayAnimationView.setAlpha(backgroundGradientColor1 != 0 ? 1.0f : 0.0f);
                backgroundPlayAnimationView.setTag(backgroundGradientColor1 != 0 ? 1 : null);
                backgroundButtonsContainer.addView(backgroundPlayAnimationView, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
                backgroundPlayAnimationView.setOnClickListener(new View.OnClickListener() {

                    int rotation = 0;

                    @Override
                    public void onClick(View v) {
                        Drawable background = backgroundImage.getBackground();
                        backgroundPlayAnimationImageView.setRotation(rotation);
                        rotation -= 45;
                        backgroundPlayAnimationImageView.animate().rotationBy(-45).setDuration(300).setInterpolator(CubicBezierInterpolator.EASE_OUT).start();
                        if (background instanceof MotionBackgroundDrawable) {
                            MotionBackgroundDrawable motionBackgroundDrawable = (MotionBackgroundDrawable) background;
                            motionBackgroundDrawable.switchToNextPosition();
                        } else {
                            onColorsRotate();
                        }
                    }
                });
                backgroundPlayAnimationImageView = new ImageView(context);
                backgroundPlayAnimationImageView.setScaleType(ImageView.ScaleType.CENTER);
                backgroundPlayAnimationImageView.setImageResource(R.drawable.bg_rotate_large);
                backgroundPlayAnimationView.addView(backgroundPlayAnimationImageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
            }
            for (int a = 0; a < textsCount; a++) {
                final int num = a;
                backgroundCheckBoxView[a] = new WallpaperCheckBoxView(context, screenType != SCREEN_TYPE_ACCENT_COLOR && !(currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) || a != 0, backgroundImage);
                backgroundCheckBoxView[a].setBackgroundColor(backgroundColor);
                backgroundCheckBoxView[a].setText(texts[a], textSizes[a], maxTextSize);
                if (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
                    if (a == 1) {
                        backgroundCheckBoxView[a].setChecked(selectedPattern != null || accent != null && !TextUtils.isEmpty(accent.patternSlug), false);
                    } else if (a == 2) {
                        backgroundCheckBoxView[a].setChecked(isMotion, false);
                    }
                } else {
                    backgroundCheckBoxView[a].setChecked(a == 0 ? isBlurred : isMotion, false);
                }
                int width = maxTextSize + AndroidUtilities.dp(14 * 2 + 28);
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER;
                if (textsCount == 3) {
                    if (a == 0 || a == 2) {
                        layoutParams.leftMargin = width / 2 + AndroidUtilities.dp(10);
                    } else {
                        layoutParams.rightMargin = width / 2 + AndroidUtilities.dp(10);
                    }
                } else {
                    if (a == 1) {
                        layoutParams.leftMargin = width / 2 + AndroidUtilities.dp(10);
                    } else {
                        layoutParams.rightMargin = width / 2 + AndroidUtilities.dp(10);
                    }
                }
                backgroundButtonsContainer.addView(backgroundCheckBoxView[a], layoutParams);
                WallpaperCheckBoxView view = backgroundCheckBoxView[a];
                backgroundCheckBoxView[a].setOnClickListener(v -> {
                    if (backgroundButtonsContainer.getAlpha() != 1.0f || patternViewAnimation != null) {
                        return;
                    }
                    if ((screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) && num == 2) {
                        view.setChecked(!view.isChecked(), true);
                        isMotion = view.isChecked();
                        parallaxEffect.setEnabled(isMotion);
                        animateMotionChange();
                    } else if (num == 1 && (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper)) {
                        if (backgroundCheckBoxView[1].isChecked()) {
                            lastSelectedPattern = selectedPattern;
                            backgroundImage.setImageDrawable(null);
                            selectedPattern = null;
                            isMotion = false;
                            updateButtonState(false, true);
                            animateMotionChange();
                            if (patternLayout[1].getVisibility() == View.VISIBLE) {
                                if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
                                    showPatternsView(0, true, true);
                                } else {
                                    showPatternsView(num, patternLayout[num].getVisibility() != View.VISIBLE, true);
                                }
                            }
                        } else {
                            selectPattern(lastSelectedPattern != null ? -1 : 0);
                            if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
                                showPatternsView(1, true, true);
                            } else {
                                showPatternsView(num, patternLayout[num].getVisibility() != View.VISIBLE, true);
                            }
                        }
                        backgroundCheckBoxView[1].setChecked(selectedPattern != null, true);
                        updateSelectedPattern(true);
                        patternsListView.invalidateViews();
                        updateMotionButton();
                    } else if (currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
                        showPatternsView(num, patternLayout[num].getVisibility() != View.VISIBLE, true);
                    } else if (screenType != SCREEN_TYPE_ACCENT_COLOR) {
                        view.setChecked(!view.isChecked(), true);
                        if (num == 0) {
                            isBlurred = view.isChecked();
                            if (isBlurred) {
                                backgroundImage.getImageReceiver().setForceCrossfade(true);
                            }
                            updateBlurred();
                        } else {
                            isMotion = view.isChecked();
                            parallaxEffect.setEnabled(isMotion);
                            animateMotionChange();
                        }
                    }
                });
                if (a == 2) {
                    backgroundCheckBoxView[a].setAlpha(0.0f);
                    backgroundCheckBoxView[a].setVisibility(View.INVISIBLE);
                }
            }
        }
        if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
            String[] texts = new String[2];
            int[] textSizes = new int[2];
            messagesCheckBoxView = new WallpaperCheckBoxView[2];
            int maxTextSize = 0;
            messagesButtonsContainer = new FrameLayout(context);
            texts[0] = LocaleController.getString("BackgroundAnimate", R.string.BackgroundAnimate);
            texts[1] = LocaleController.getString("BackgroundColors", R.string.BackgroundColors);
            for (int a = 0; a < texts.length; a++) {
                textSizes[a] = (int) Math.ceil(textPaint.measureText(texts[a]));
                maxTextSize = Math.max(maxTextSize, textSizes[a]);
            }
            messagesPlayAnimationView = new FrameLayout(context) {

                private RectF rect = new RectF();

                @Override
                protected void onDraw(Canvas canvas) {
                    rect.set(0, 0, getMeasuredWidth(), getMeasuredHeight());
                    Theme.applyServiceShaderMatrixForView(messagesPlayAnimationView, backgroundImage);
                    canvas.drawRoundRect(rect, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Theme.chat_actionBackgroundPaint);
                    if (Theme.hasGradientService()) {
                        canvas.drawRoundRect(rect, getMeasuredHeight() / 2, getMeasuredHeight() / 2, Theme.chat_actionBackgroundGradientDarkenPaint);
                    }
                }
            };
            messagesPlayAnimationView.setWillNotDraw(false);
            messagesPlayAnimationView.setVisibility(accent.myMessagesGradientAccentColor1 != 0 ? View.VISIBLE : View.INVISIBLE);
            messagesPlayAnimationView.setScaleX(accent.myMessagesGradientAccentColor1 != 0 ? 1.0f : 0.1f);
            messagesPlayAnimationView.setScaleY(accent.myMessagesGradientAccentColor1 != 0 ? 1.0f : 0.1f);
            messagesPlayAnimationView.setAlpha(accent.myMessagesGradientAccentColor1 != 0 ? 1.0f : 0.0f);
            messagesButtonsContainer.addView(messagesPlayAnimationView, LayoutHelper.createFrame(48, 48, Gravity.CENTER));
            messagesPlayAnimationView.setOnClickListener(new View.OnClickListener() {

                int rotation = 0;

                @Override
                public void onClick(View v) {
                    messagesPlayAnimationImageView.setRotation(rotation);
                    rotation -= 45;
                    messagesPlayAnimationImageView.animate().rotationBy(-45).setDuration(300).setInterpolator(CubicBezierInterpolator.EASE_OUT).start();
                    if (accent.myMessagesAnimated) {
                        if (msgOutDrawable.getMotionBackgroundDrawable() != null) {
                            msgOutDrawable.getMotionBackgroundDrawable().switchToNextPosition();
                        }
                    } else {
                        int temp;
                        if (accent.myMessagesGradientAccentColor3 != 0) {
                            temp = accent.myMessagesAccentColor != 0 ? accent.myMessagesAccentColor : accent.accentColor;
                            accent.myMessagesAccentColor = accent.myMessagesGradientAccentColor1;
                            accent.myMessagesGradientAccentColor1 = accent.myMessagesGradientAccentColor2;
                            accent.myMessagesGradientAccentColor2 = accent.myMessagesGradientAccentColor3;
                            accent.myMessagesGradientAccentColor3 = temp;
                        } else {
                            temp = accent.myMessagesAccentColor != 0 ? accent.myMessagesAccentColor : accent.accentColor;
                            accent.myMessagesAccentColor = accent.myMessagesGradientAccentColor1;
                            accent.myMessagesGradientAccentColor1 = accent.myMessagesGradientAccentColor2;
                            accent.myMessagesGradientAccentColor2 = temp;
                        }
                        colorPicker.setColor(accent.myMessagesGradientAccentColor3, 3);
                        colorPicker.setColor(accent.myMessagesGradientAccentColor2, 2);
                        colorPicker.setColor(accent.myMessagesGradientAccentColor1, 1);
                        colorPicker.setColor(accent.myMessagesAccentColor != 0 ? accent.myMessagesAccentColor : accent.accentColor, 0);
                        messagesCheckBoxView[1].setColor(0, accent.myMessagesAccentColor);
                        messagesCheckBoxView[1].setColor(1, accent.myMessagesGradientAccentColor1);
                        messagesCheckBoxView[1].setColor(2, accent.myMessagesGradientAccentColor2);
                        messagesCheckBoxView[1].setColor(3, accent.myMessagesGradientAccentColor3);
                        Theme.refreshThemeColors(true, true);
                        listView2.invalidateViews();
                    }
                }
            });
            messagesPlayAnimationImageView = new ImageView(context);
            messagesPlayAnimationImageView.setScaleType(ImageView.ScaleType.CENTER);
            messagesPlayAnimationImageView.setImageResource(R.drawable.bg_rotate_large);
            messagesPlayAnimationView.addView(messagesPlayAnimationImageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
            for (int a = 0; a < 2; a++) {
                final int num = a;
                messagesCheckBoxView[a] = new WallpaperCheckBoxView(context, a == 0, backgroundImage);
                messagesCheckBoxView[a].setText(texts[a], textSizes[a], maxTextSize);
                if (a == 0) {
                    messagesCheckBoxView[a].setChecked(accent.myMessagesAnimated, false);
                }
                int width = maxTextSize + AndroidUtilities.dp(14 * 2 + 28);
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER;
                if (a == 1) {
                    layoutParams.leftMargin = width / 2 + AndroidUtilities.dp(10);
                } else {
                    layoutParams.rightMargin = width / 2 + AndroidUtilities.dp(10);
                }
                messagesButtonsContainer.addView(messagesCheckBoxView[a], layoutParams);
                WallpaperCheckBoxView view = messagesCheckBoxView[a];
                messagesCheckBoxView[a].setOnClickListener(v -> {
                    if (messagesButtonsContainer.getAlpha() != 1.0f) {
                        return;
                    }
                    if (num == 0) {
                        view.setChecked(!view.isChecked(), true);
                        accent.myMessagesAnimated = view.isChecked();
                        Theme.refreshThemeColors(true, true);
                        listView2.invalidateViews();
                    }
                });
            }
        }
        if (screenType == SCREEN_TYPE_ACCENT_COLOR || currentWallpaper instanceof WallpapersListActivity.ColorWallpaper) {
            isBlurred = false;
            for (int a = 0; a < 2; a++) {
                final int num = a;
                patternLayout[a] = new FrameLayout(context) {

                    @Override
                    public void onDraw(Canvas canvas) {
                        if (num == 0) {
                            sheetDrawable.setBounds(colorPicker.getLeft() - paddings.left, 0, colorPicker.getRight() + paddings.right, getMeasuredHeight());
                        } else {
                            sheetDrawable.setBounds(-paddings.left, 0, getMeasuredWidth() + paddings.right, getMeasuredHeight());
                        }
                        sheetDrawable.draw(canvas);
                    }
                };
                if (a == 1 || screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
                    patternLayout[a].setVisibility(View.INVISIBLE);
                }
                patternLayout[a].setWillNotDraw(false);
                FrameLayout.LayoutParams layoutParams;
                if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
                    layoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, a == 0 ? 321 : 316, Gravity.LEFT | Gravity.BOTTOM);
                } else {
                    layoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, a == 0 ? 273 : 316, Gravity.LEFT | Gravity.BOTTOM);
                }
                if (a == 0) {
                    layoutParams.height += AndroidUtilities.dp(12) + paddings.top;
                    patternLayout[a].setPadding(0, AndroidUtilities.dp(12) + paddings.top, 0, 0);
                }
                page2.addView(patternLayout[a], layoutParams);
                if (a == 1 || screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
                    patternsButtonsContainer[a] = new FrameLayout(context) {

                        @Override
                        public void onDraw(Canvas canvas) {
                            int bottom = Theme.chat_composeShadowDrawable.getIntrinsicHeight();
                            Theme.chat_composeShadowDrawable.setBounds(0, 0, getMeasuredWidth(), bottom);
                            Theme.chat_composeShadowDrawable.draw(canvas);
                            canvas.drawRect(0, bottom, getMeasuredWidth(), getMeasuredHeight(), Theme.chat_composeBackgroundPaint);
                        }
                    };
                    patternsButtonsContainer[a].setWillNotDraw(false);
                    patternsButtonsContainer[a].setPadding(0, AndroidUtilities.dp(3), 0, 0);
                    patternsButtonsContainer[a].setClickable(true);
                    patternLayout[a].addView(patternsButtonsContainer[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
                    patternsCancelButton[a] = new TextView(context);
                    patternsCancelButton[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
                    patternsCancelButton[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
                    patternsCancelButton[a].setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText));
                    patternsCancelButton[a].setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase());
                    patternsCancelButton[a].setGravity(Gravity.CENTER);
                    patternsCancelButton[a].setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), 0);
                    patternsCancelButton[a].setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 0));
                    patternsButtonsContainer[a].addView(patternsCancelButton[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
                    patternsCancelButton[a].setOnClickListener(v -> {
                        if (patternViewAnimation != null) {
                            return;
                        }
                        if (num == 0) {
                            backgroundRotation = previousBackgroundRotation;
                            setBackgroundColor(previousBackgroundGradientColor3, 3, true, true);
                            setBackgroundColor(previousBackgroundGradientColor2, 2, true, true);
                            setBackgroundColor(previousBackgroundGradientColor1, 1, true, true);
                            setBackgroundColor(previousBackgroundColor, 0, true, true);
                        } else {
                            selectedPattern = previousSelectedPattern;
                            if (selectedPattern == null) {
                                backgroundImage.setImageDrawable(null);
                            } else {
                                backgroundImage.setImage(ImageLocation.getForDocument(selectedPattern.document), imageFilter, null, null, "jpg", selectedPattern.document.size, 1, selectedPattern);
                            }
                            backgroundCheckBoxView[1].setChecked(selectedPattern != null, false);
                            currentIntensity = previousIntensity;
                            intensitySeekBar.setProgress(currentIntensity);
                            backgroundImage.getImageReceiver().setAlpha(currentIntensity);
                            updateButtonState(false, true);
                            updateSelectedPattern(true);
                        }
                        if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
                            showPatternsView(num, false, true);
                        } else {
                            if (selectedPattern == null) {
                                if (isMotion) {
                                    isMotion = false;
                                    backgroundCheckBoxView[0].setChecked(false, true);
                                    animateMotionChange();
                                }
                                updateMotionButton();
                            }
                            showPatternsView(0, true, true);
                        }
                    });
                    patternsSaveButton[a] = new TextView(context);
                    patternsSaveButton[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
                    patternsSaveButton[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
                    patternsSaveButton[a].setTextColor(Theme.getColor(Theme.key_chat_fieldOverlayText));
                    patternsSaveButton[a].setText(LocaleController.getString("ApplyTheme", R.string.ApplyTheme).toUpperCase());
                    patternsSaveButton[a].setGravity(Gravity.CENTER);
                    patternsSaveButton[a].setPadding(AndroidUtilities.dp(21), 0, AndroidUtilities.dp(21), 0);
                    patternsSaveButton[a].setBackgroundDrawable(Theme.createSelectorDrawable(Theme.getColor(Theme.key_listSelector), 0));
                    patternsButtonsContainer[a].addView(patternsSaveButton[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP));
                    patternsSaveButton[a].setOnClickListener(v -> {
                        if (patternViewAnimation != null) {
                            return;
                        }
                        if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
                            showPatternsView(num, false, true);
                        } else {
                            showPatternsView(0, true, true);
                        }
                    });
                }
                if (a == 1) {
                    TextView titleView = new TextView(context);
                    titleView.setLines(1);
                    titleView.setSingleLine(true);
                    titleView.setText(LocaleController.getString("BackgroundChoosePattern", R.string.BackgroundChoosePattern));
                    titleView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
                    titleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
                    titleView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
                    titleView.setPadding(AndroidUtilities.dp(21), AndroidUtilities.dp(6), AndroidUtilities.dp(21), AndroidUtilities.dp(8));
                    titleView.setEllipsize(TextUtils.TruncateAt.MIDDLE);
                    titleView.setGravity(Gravity.CENTER_VERTICAL);
                    patternLayout[a].addView(titleView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP, 0, 21, 0, 0));
                    patternsListView = new RecyclerListView(context) {

                        @Override
                        public boolean onTouchEvent(MotionEvent event) {
                            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                                getParent().requestDisallowInterceptTouchEvent(true);
                            }
                            return super.onTouchEvent(event);
                        }
                    };
                    patternsListView.setLayoutManager(patternsLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
                    patternsListView.setAdapter(patternsAdapter = new PatternsAdapter(context));
                    patternsListView.addItemDecoration(new RecyclerView.ItemDecoration() {

                        @Override
                        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                            int position = parent.getChildAdapterPosition(view);
                            outRect.left = AndroidUtilities.dp(12);
                            outRect.bottom = outRect.top = 0;
                            if (position == state.getItemCount() - 1) {
                                outRect.right = AndroidUtilities.dp(12);
                            }
                        }
                    });
                    patternLayout[a].addView(patternsListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 100, Gravity.LEFT | Gravity.TOP, 0, 76, 0, 0));
                    patternsListView.setOnItemClickListener((view, position) -> {
                        boolean previousMotion = selectedPattern != null;
                        selectPattern(position);
                        if (previousMotion == (selectedPattern == null)) {
                            animateMotionChange();
                            updateMotionButton();
                        }
                        updateSelectedPattern(true);
                        backgroundCheckBoxView[1].setChecked(selectedPattern != null, true);
                        patternsListView.invalidateViews();
                        int left = view.getLeft();
                        int right = view.getRight();
                        int extra = AndroidUtilities.dp(52);
                        if (left - extra < 0) {
                            patternsListView.smoothScrollBy(left - extra, 0);
                        } else if (right + extra > patternsListView.getMeasuredWidth()) {
                            patternsListView.smoothScrollBy(right + extra - patternsListView.getMeasuredWidth(), 0);
                        }
                    });
                    intensityCell = new HeaderCell(context);
                    intensityCell.setText(LocaleController.getString("BackgroundIntensity", R.string.BackgroundIntensity));
                    patternLayout[a].addView(intensityCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 0, 175, 0, 0));
                    intensitySeekBar = new SeekBarView(context) {

                        @Override
                        public boolean onTouchEvent(MotionEvent event) {
                            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                                getParent().requestDisallowInterceptTouchEvent(true);
                            }
                            return super.onTouchEvent(event);
                        }
                    };
                    intensitySeekBar.setProgress(currentIntensity);
                    intensitySeekBar.setReportChanges(true);
                    intensitySeekBar.setDelegate(new SeekBarView.SeekBarViewDelegate() {

                        @Override
                        public void onSeekBarDrag(boolean stop, float progress) {
                            currentIntensity = progress;
                            backgroundImage.getImageReceiver().setAlpha(Math.abs(currentIntensity));
                            backgroundImage.invalidate();
                            patternsListView.invalidateViews();
                            if (currentIntensity >= 0) {
                                if (Build.VERSION.SDK_INT >= 29 && backgroundImage.getBackground() instanceof MotionBackgroundDrawable) {
                                    backgroundImage.getImageReceiver().setBlendMode(BlendMode.SOFT_LIGHT);
                                }
                                backgroundImage.getImageReceiver().setGradientBitmap(null);
                            } else {
                                if (Build.VERSION.SDK_INT >= 29) {
                                    backgroundImage.getImageReceiver().setBlendMode(null);
                                }
                                if (backgroundImage.getBackground() instanceof MotionBackgroundDrawable) {
                                    MotionBackgroundDrawable motionBackgroundDrawable = (MotionBackgroundDrawable) backgroundImage.getBackground();
                                    backgroundImage.getImageReceiver().setGradientBitmap(motionBackgroundDrawable.getBitmap());
                                }
                            }
                        }

                        @Override
                        public void onSeekBarPressed(boolean pressed) {
                        }
                    });
                    patternLayout[a].addView(intensitySeekBar, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 5, 211, 5, 0));
                } else {
                    colorPicker = new ColorPicker(context, editingTheme, new ColorPicker.ColorPickerDelegate() {

                        @Override
                        public void setColor(int color, int num, boolean applyNow) {
                            if (screenType == SCREEN_TYPE_CHANGE_BACKGROUND) {
                                setBackgroundColor(color, num, applyNow, true);
                            } else {
                                scheduleApplyColor(color, num, applyNow);
                            }
                        }

                        @Override
                        public void openThemeCreate(boolean share) {
                            if (share) {
                                if (accent.info == null) {
                                    finishFragment();
                                    MessagesController.getInstance(currentAccount).saveThemeToServer(accent.parentTheme, accent);
                                    NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needShareTheme, accent.parentTheme, accent);
                                } else {
                                    String link = "https://" + MessagesController.getInstance(currentAccount).linkPrefix + "/addtheme/" + accent.info.slug;
                                    showDialog(new ShareAlert(getParentActivity(), null, link, false, link, false));
                                }
                            } else {
                                AlertsCreator.createThemeCreateDialog(ThemePreviewActivity.this, 1, null, null);
                            }
                        }

                        @Override
                        public void deleteTheme() {
                            if (getParentActivity() == null) {
                                return;
                            }
                            AlertDialog.Builder builder1 = new AlertDialog.Builder(getParentActivity());
                            builder1.setTitle(LocaleController.getString("DeleteThemeTitle", R.string.DeleteThemeTitle));
                            builder1.setMessage(LocaleController.getString("DeleteThemeAlert", R.string.DeleteThemeAlert));
                            builder1.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialogInterface, i) -> {
                                Theme.deleteThemeAccent(applyingTheme, accent, true);
                                Theme.applyPreviousTheme();
                                Theme.refreshThemeColors();
                                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, applyingTheme, nightTheme, null, -1);
                                finishFragment();
                            });
                            builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                            AlertDialog alertDialog = builder1.create();
                            showDialog(alertDialog);
                            TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                            if (button != null) {
                                button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
                            }
                        }

                        @Override
                        public void rotateColors() {
                            onColorsRotate();
                        }

                        @Override
                        public int getDefaultColor(int num) {
                            if (colorType == 3 && applyingTheme.firstAccentIsDefault && num == 0) {
                                Theme.ThemeAccent accent = applyingTheme.themeAccentsMap.get(Theme.DEFALT_THEME_ACCENT_ID);
                                return accent != null ? accent.myMessagesAccentColor : 0;
                            }
                            return 0;
                        }

                        @Override
                        public boolean hasChanges() {
                            return ThemePreviewActivity.this.hasChanges(colorType);
                        }
                    });
                    if (screenType == SCREEN_TYPE_ACCENT_COLOR) {
                        patternLayout[a].addView(colorPicker, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_HORIZONTAL));
                        if (applyingTheme.isDark()) {
                            colorPicker.setMinBrightness(0.2f);
                        } else {
                            colorPicker.setMinBrightness(0.05f);
                            colorPicker.setMaxBrightness(0.8f);
                        }
                        int colorsCount = accent.accentColor2 != 0 ? 2 : 1;
                        colorPicker.setType(1, hasChanges(1), 2, colorsCount, false, 0, false);
                        colorPicker.setColor(accent.accentColor, 0);
                        if (accent.accentColor2 != 0) {
                            colorPicker.setColor(accent.accentColor2, 1);
                        }
                    } else {
                        patternLayout[a].addView(colorPicker, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER_HORIZONTAL, 0, 0, 0, 48));
                    }
                }
            }
        }
        updateButtonState(false, false);
        if (!backgroundImage.getImageReceiver().hasBitmapImage()) {
            page2.setBackgroundColor(0xff000000);
        }
        if (screenType != SCREEN_TYPE_ACCENT_COLOR && !(currentWallpaper instanceof WallpapersListActivity.ColorWallpaper)) {
            backgroundImage.getImageReceiver().setCrossfadeWithOldImage(true);
        }
    }
    listView2.setAdapter(messagesAdapter);
    frameLayout = new FrameLayout(context) {

        private int[] loc = new int[2];

        @Override
        public void invalidate() {
            super.invalidate();
            if (page2 != null) {
                page2.invalidate();
            }
        }

        @Override
        protected void onDraw(Canvas canvas) {
            if (!AndroidUtilities.usingHardwareInput) {
                getLocationInWindow(loc);
                if (Build.VERSION.SDK_INT < 21 && !AndroidUtilities.isTablet()) {
                    loc[1] -= AndroidUtilities.statusBarHeight;
                }
                if (actionBar2.getTranslationY() != loc[1]) {
                    actionBar2.setTranslationY(-loc[1]);
                    page2.invalidate();
                }
                if (SystemClock.elapsedRealtime() < watchForKeyboardEndTime) {
                    invalidate();
                }
            }
        }
    };
    frameLayout.setWillNotDraw(false);
    fragmentView = frameLayout;
    frameLayout.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener = () -> {
        watchForKeyboardEndTime = SystemClock.elapsedRealtime() + 1500;
        frameLayout.invalidate();
    });
    viewPager = new ViewPager(context);
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            dotsContainer.invalidate();
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
    viewPager.setAdapter(new PagerAdapter() {

        @Override
        public int getCount() {
            return screenType != SCREEN_TYPE_PREVIEW ? 1 : 2;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return object == view;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_UNCHANGED;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = position == 0 ? page2 : page1;
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public void unregisterDataSetObserver(DataSetObserver observer) {
            if (observer != null) {
                super.unregisterDataSetObserver(observer);
            }
        }
    });
    AndroidUtilities.setViewPagerEdgeEffectColor(viewPager, Theme.getColor(Theme.key_actionBarDefault));
    frameLayout.addView(viewPager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 0, 0, screenType == SCREEN_TYPE_PREVIEW ? 48 : 0));
    undoView = new UndoView(context, this);
    undoView.setAdditionalTranslationY(AndroidUtilities.dp(51));
    frameLayout.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    if (screenType == SCREEN_TYPE_PREVIEW) {
        View shadow = new View(context);
        shadow.setBackgroundColor(Theme.getColor(Theme.key_dialogShadowLine));
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1, Gravity.LEFT | Gravity.BOTTOM);
        layoutParams.bottomMargin = AndroidUtilities.dp(48);
        frameLayout.addView(shadow, layoutParams);
        saveButtonsContainer = new FrameLayout(context);
        saveButtonsContainer.setBackgroundColor(getButtonsColor(Theme.key_windowBackgroundWhite));
        frameLayout.addView(saveButtonsContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
        dotsContainer = new View(context) {

            private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

            @Override
            protected void onDraw(Canvas canvas) {
                int selected = viewPager.getCurrentItem();
                paint.setColor(getButtonsColor(Theme.key_chat_fieldOverlayText));
                for (int a = 0; a < 2; a++) {
                    paint.setAlpha(a == selected ? 255 : 127);
                    canvas.drawCircle(AndroidUtilities.dp(3 + 15 * a), AndroidUtilities.dp(4), AndroidUtilities.dp(3), paint);
                }
            }
        };
        saveButtonsContainer.addView(dotsContainer, LayoutHelper.createFrame(22, 8, Gravity.CENTER));
        cancelButton = new TextView(context);
        cancelButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        cancelButton.setTextColor(getButtonsColor(Theme.key_chat_fieldOverlayText));
        cancelButton.setGravity(Gravity.CENTER);
        cancelButton.setBackgroundDrawable(Theme.createSelectorDrawable(0x0f000000, 0));
        cancelButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0);
        cancelButton.setText(LocaleController.getString("Cancel", R.string.Cancel).toUpperCase());
        cancelButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        saveButtonsContainer.addView(cancelButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
        cancelButton.setOnClickListener(v -> cancelThemeApply(false));
        doneButton = new TextView(context);
        doneButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        doneButton.setTextColor(getButtonsColor(Theme.key_chat_fieldOverlayText));
        doneButton.setGravity(Gravity.CENTER);
        doneButton.setBackgroundDrawable(Theme.createSelectorDrawable(0x0f000000, 0));
        doneButton.setPadding(AndroidUtilities.dp(29), 0, AndroidUtilities.dp(29), 0);
        doneButton.setText(LocaleController.getString("ApplyTheme", R.string.ApplyTheme).toUpperCase());
        doneButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        saveButtonsContainer.addView(doneButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.RIGHT));
        doneButton.setOnClickListener(v -> {
            Theme.ThemeInfo previousTheme = Theme.getPreviousTheme();
            if (previousTheme == null) {
                return;
            }
            Theme.ThemeAccent previousAccent;
            if (previousTheme != null && previousTheme.prevAccentId >= 0) {
                previousAccent = previousTheme.themeAccentsMap.get(previousTheme.prevAccentId);
            } else {
                previousAccent = previousTheme.getAccent(false);
            }
            if (accent != null) {
                saveAccentWallpaper();
                Theme.saveThemeAccents(applyingTheme, true, false, false, false);
                Theme.clearPreviousTheme();
                Theme.applyTheme(applyingTheme, nightTheme);
                parentLayout.rebuildAllFragmentViews(false, false);
            } else {
                parentLayout.rebuildAllFragmentViews(false, false);
                Theme.applyThemeFile(new File(applyingTheme.pathToFile), applyingTheme.name, applyingTheme.info, false);
                MessagesController.getInstance(applyingTheme.account).saveTheme(applyingTheme, null, false, false);
                SharedPreferences.Editor editor = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Activity.MODE_PRIVATE).edit();
                editor.putString("lastDayTheme", applyingTheme.getKey());
                editor.commit();
            }
            finishFragment();
            if (screenType == SCREEN_TYPE_PREVIEW) {
                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.didApplyNewTheme, previousTheme, previousAccent, deleteOnCancel);
            }
        });
    }
    if (screenType == SCREEN_TYPE_ACCENT_COLOR && !Theme.hasCustomWallpaper() && accent.backgroundOverrideColor != 0x100000000L) {
        selectColorType(2);
    }
    themeDescriptions = getThemeDescriptionsInternal();
    setCurrentImage(true);
    updatePlayAnimationView(false);
    if (showColor) {
        showPatternsView(0, true, false);
    }
    return fragmentView;
}
Also used : SvgHelper(org.telegram.messenger.SvgHelper) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) MediaActionDrawable(org.telegram.ui.Components.MediaActionDrawable) StateListAnimator(android.animation.StateListAnimator) Shader(android.graphics.Shader) Canvas(android.graphics.Canvas) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) UndoView(org.telegram.ui.Components.UndoView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationCenter(org.telegram.messenger.NotificationCenter) MenuDrawable(org.telegram.ui.ActionBar.MenuDrawable) Outline(android.graphics.Outline) TextPaint(android.text.TextPaint) HintView(org.telegram.ui.Components.HintView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) FileLoader(org.telegram.messenger.FileLoader) ViewPager(androidx.viewpager.widget.ViewPager) SystemClock(android.os.SystemClock) AlertsCreator(org.telegram.ui.Components.AlertsCreator) BackgroundGradientDrawable(org.telegram.ui.Components.BackgroundGradientDrawable) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) GradientDrawable(android.graphics.drawable.GradientDrawable) ColorPicker(org.telegram.ui.Components.ColorPicker) DialogCell(org.telegram.ui.Cells.DialogCell) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) File(java.io.File) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) MessagesStorage(org.telegram.messenger.MessagesStorage) Configuration(android.content.res.Configuration) WallpaperParallaxEffect(org.telegram.ui.Components.WallpaperParallaxEffect) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) EditText(android.widget.EditText) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Rect(android.graphics.Rect) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) RadialProgress2(org.telegram.ui.Components.RadialProgress2) WallpaperCheckBoxView(org.telegram.ui.Components.WallpaperCheckBoxView) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) Animator(android.animation.Animator) ApplicationLoader(org.telegram.messenger.ApplicationLoader) PatternCell(org.telegram.ui.Cells.PatternCell) MediaController(org.telegram.messenger.MediaController) View(android.view.View) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) RecyclerView(androidx.recyclerview.widget.RecyclerView) DataSetObserver(android.database.DataSetObserver) RectF(android.graphics.RectF) ImageLoader(org.telegram.messenger.ImageLoader) Utilities(org.telegram.messenger.Utilities) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) BitmapDrawable(android.graphics.drawable.BitmapDrawable) ChatActionCell(org.telegram.ui.Cells.ChatActionCell) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ViewGroup(android.view.ViewGroup) ShareAlert(org.telegram.ui.Components.ShareAlert) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) UserConfig(org.telegram.messenger.UserConfig) List(java.util.List) TextView(android.widget.TextView) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) Context(android.content.Context) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) Theme(org.telegram.ui.ActionBar.Theme) PagerAdapter(androidx.viewpager.widget.PagerAdapter) ViewOutlineProvider(android.view.ViewOutlineProvider) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) ActionBar(org.telegram.ui.ActionBar.ActionBar) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) SeekBarView(org.telegram.ui.Components.SeekBarView) DownloadController(org.telegram.messenger.DownloadController) DialogInterface(android.content.DialogInterface) LongSparseArray(androidx.collection.LongSparseArray) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) MessagesController(org.telegram.messenger.MessagesController) BlendMode(android.graphics.BlendMode) Bitmap(android.graphics.Bitmap) ViewTreeObserver(android.view.ViewTreeObserver) Activity(android.app.Activity) ImageReceiver(org.telegram.messenger.ImageReceiver) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LoadingCell(org.telegram.ui.Cells.LoadingCell) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) HeaderCell(org.telegram.ui.Cells.HeaderCell) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) EditText(android.widget.EditText) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Rect(android.graphics.Rect) MenuDrawable(org.telegram.ui.ActionBar.MenuDrawable) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) MediaActionDrawable(org.telegram.ui.Components.MediaActionDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) MenuDrawable(org.telegram.ui.ActionBar.MenuDrawable) BackgroundGradientDrawable(org.telegram.ui.Components.BackgroundGradientDrawable) GradientDrawable(android.graphics.drawable.GradientDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) SeekBarView(org.telegram.ui.Components.SeekBarView) ViewPager(androidx.viewpager.widget.ViewPager) MessageObject(org.telegram.messenger.MessageObject) ShareAlert(org.telegram.ui.Components.ShareAlert) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) WallpaperCheckBoxView(org.telegram.ui.Components.WallpaperCheckBoxView) UndoView(org.telegram.ui.Components.UndoView) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) SharedPreferences(android.content.SharedPreferences) Outline(android.graphics.Outline) ViewOutlineProvider(android.view.ViewOutlineProvider) RectF(android.graphics.RectF) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) SuppressLint(android.annotation.SuppressLint) Theme(org.telegram.ui.ActionBar.Theme) RecyclerView(androidx.recyclerview.widget.RecyclerView) MediaController(org.telegram.messenger.MediaController) ColorPicker(org.telegram.ui.Components.ColorPicker) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TLRPC(org.telegram.tgnet.TLRPC) PagerAdapter(androidx.viewpager.widget.PagerAdapter) ImageReceiver(org.telegram.messenger.ImageReceiver) RadialProgress2(org.telegram.ui.Components.RadialProgress2) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) BackupImageView(org.telegram.ui.Components.BackupImageView) TextView(android.widget.TextView) ImageView(android.widget.ImageView) BackupImageView(org.telegram.ui.Components.BackupImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) WallpaperParallaxEffect(org.telegram.ui.Components.WallpaperParallaxEffect) Canvas(android.graphics.Canvas) MotionBackgroundDrawable(org.telegram.ui.Components.MotionBackgroundDrawable) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) BackgroundGradientDrawable(org.telegram.ui.Components.BackgroundGradientDrawable) GradientDrawable(android.graphics.drawable.GradientDrawable) TextPaint(android.text.TextPaint) ColorDrawable(android.graphics.drawable.ColorDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) FileOutputStream(java.io.FileOutputStream) File(java.io.File) StateListAnimator(android.animation.StateListAnimator) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) Bitmap(android.graphics.Bitmap) ViewGroup(android.view.ViewGroup) ImageView(android.widget.ImageView) UndoView(org.telegram.ui.Components.UndoView) HintView(org.telegram.ui.Components.HintView) WallpaperCheckBoxView(org.telegram.ui.Components.WallpaperCheckBoxView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) SeekBarView(org.telegram.ui.Components.SeekBarView) BackupImageView(org.telegram.ui.Components.BackupImageView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) DataSetObserver(android.database.DataSetObserver) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) FrameLayout(android.widget.FrameLayout) MessageObject(org.telegram.messenger.MessageObject) SuppressLint(android.annotation.SuppressLint)

Example 12 with StateListAnimator

use of android.animation.StateListAnimator in project Telegram-FOSS by Telegram-FOSS-Team.

the class LocationActivity method createView.

@Override
public View createView(Context context) {
    searchWas = false;
    searching = false;
    searchInProgress = false;
    if (adapter != null) {
        adapter.destroy();
    }
    if (searchAdapter != null) {
        searchAdapter.destroy();
    }
    if (chatLocation != null) {
        userLocation = new Location("network");
        userLocation.setLatitude(chatLocation.geo_point.lat);
        userLocation.setLongitude(chatLocation.geo_point._long);
    } else if (messageObject != null) {
        userLocation = new Location("network");
        userLocation.setLatitude(messageObject.messageOwner.media.geo.lat);
        userLocation.setLongitude(messageObject.messageOwner.media.geo._long);
    }
    locationDenied = Build.VERSION.SDK_INT >= 23 && getParentActivity() != null && getParentActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED;
    actionBar.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground));
    actionBar.setTitleColor(Theme.getColor(Theme.key_dialogTextBlack));
    actionBar.setItemsColor(Theme.getColor(Theme.key_dialogTextBlack), false);
    actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_dialogButtonSelector), false);
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }
    actionBar.setAddToContainer(false);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == open_in) {
                try {
                    double lat = messageObject.messageOwner.media.geo.lat;
                    double lon = messageObject.messageOwner.media.geo._long;
                    getParentActivity().startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:" + lat + "," + lon + "?q=" + lat + "," + lon)));
                } catch (Exception e) {
                    FileLog.e(e);
                }
            } else if (id == share_live_location) {
                openShareLiveLocation(0);
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    if (chatLocation != null) {
        actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation));
    } else if (messageObject != null) {
        if (messageObject.isLiveLocation()) {
            actionBar.setTitle(LocaleController.getString("AttachLiveLocation", R.string.AttachLiveLocation));
        } else {
            if (messageObject.messageOwner.media.title != null && messageObject.messageOwner.media.title.length() > 0) {
                actionBar.setTitle(LocaleController.getString("SharedPlace", R.string.SharedPlace));
            } else {
                actionBar.setTitle(LocaleController.getString("ChatLocation", R.string.ChatLocation));
            }
            otherItem = menu.addItem(0, R.drawable.ic_ab_other);
            otherItem.addSubItem(open_in, R.drawable.msg_openin, LocaleController.getString("OpenInExternalApp", R.string.OpenInExternalApp));
            if (!getLocationController().isSharingLocation(dialogId)) {
                otherItem.addSubItem(share_live_location, R.drawable.menu_location, LocaleController.getString("SendLiveLocationMenu", R.string.SendLiveLocationMenu));
            }
            otherItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
        }
    } else {
        actionBar.setTitle(LocaleController.getString("ShareLocation", R.string.ShareLocation));
        if (locationType != LOCATION_TYPE_GROUP) {
            overlayView = new MapOverlayView(context);
            searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

                @Override
                public void onSearchExpand() {
                    searching = true;
                }

                @Override
                public void onSearchCollapse() {
                    searching = false;
                    searchWas = false;
                    searchAdapter.searchDelayed(null, null);
                    updateEmptyView();
                }

                @Override
                public void onTextChanged(EditText editText) {
                    if (searchAdapter == null) {
                        return;
                    }
                    String text = editText.getText().toString();
                    if (text.length() != 0) {
                        searchWas = true;
                        searchItem.setShowSearchProgress(true);
                        if (otherItem != null) {
                            otherItem.setVisibility(View.GONE);
                        }
                        listView.setVisibility(View.GONE);
                        mapViewClip.setVisibility(View.GONE);
                        if (searchListView.getAdapter() != searchAdapter) {
                            searchListView.setAdapter(searchAdapter);
                        }
                        searchListView.setVisibility(View.VISIBLE);
                        searchInProgress = searchAdapter.getItemCount() == 0;
                    } else {
                        if (otherItem != null) {
                            otherItem.setVisibility(View.VISIBLE);
                        }
                        listView.setVisibility(View.VISIBLE);
                        mapViewClip.setVisibility(View.VISIBLE);
                        searchListView.setAdapter(null);
                        searchListView.setVisibility(View.GONE);
                    }
                    updateEmptyView();
                    searchAdapter.searchDelayed(text, userLocation);
                }
            });
            searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
            searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search));
            EditTextBoldCursor editText = searchItem.getSearchField();
            editText.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
            editText.setCursorColor(Theme.getColor(Theme.key_dialogTextBlack));
            editText.setHintTextColor(Theme.getColor(Theme.key_chat_messagePanelHint));
        }
    }
    fragmentView = new FrameLayout(context) {

        private boolean first = true;

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            if (changed) {
                fixLayoutInternal(first);
                first = false;
            } else {
                updateClipView(true);
            }
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == actionBar && parentLayout != null) {
                parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
            }
            return result;
        }
    };
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    fragmentView.setBackgroundColor(Theme.getColor(Theme.key_dialogBackground));
    shadowDrawable = context.getResources().getDrawable(R.drawable.sheet_shadow_round).mutate();
    shadowDrawable.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogBackground), PorterDuff.Mode.MULTIPLY));
    Rect padding = new Rect();
    shadowDrawable.getPadding(padding);
    FrameLayout.LayoutParams layoutParams;
    if (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) {
        layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(21) + padding.top);
    } else {
        layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtilities.dp(6) + padding.top);
    }
    layoutParams.gravity = Gravity.LEFT | Gravity.BOTTOM;
    mapViewClip = new FrameLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            if (overlayView != null) {
                overlayView.updatePositions();
            }
        }
    };
    mapViewClip.setBackgroundDrawable(new MapPlaceholderDrawable());
    if (messageObject == null && (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE)) {
        searchAreaButton = new SearchButton(context);
        searchAreaButton.setTranslationX(-AndroidUtilities.dp(80));
        Drawable drawable = Theme.createSimpleSelectorRoundRectDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
        if (Build.VERSION.SDK_INT < 21) {
            Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.places_btn).mutate();
            shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
            CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, AndroidUtilities.dp(2), AndroidUtilities.dp(2));
            combinedDrawable.setFullsize(true);
            drawable = combinedDrawable;
        } else {
            StateListAnimator animator = new StateListAnimator();
            animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
            animator.addState(new int[] {}, ObjectAnimator.ofFloat(searchAreaButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
            searchAreaButton.setStateListAnimator(animator);
            searchAreaButton.setOutlineProvider(new ViewOutlineProvider() {

                @SuppressLint("NewApi")
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setRoundRect(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight(), view.getMeasuredHeight() / 2);
                }
            });
        }
        searchAreaButton.setBackgroundDrawable(drawable);
        searchAreaButton.setTextColor(Theme.getColor(Theme.key_location_actionActiveIcon));
        searchAreaButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
        searchAreaButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        searchAreaButton.setText(LocaleController.getString("PlacesInThisArea", R.string.PlacesInThisArea));
        searchAreaButton.setGravity(Gravity.CENTER);
        searchAreaButton.setPadding(AndroidUtilities.dp(20), 0, AndroidUtilities.dp(20), 0);
        mapViewClip.addView(searchAreaButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.CENTER_HORIZONTAL | Gravity.TOP, 80, 12, 80, 0));
        searchAreaButton.setOnClickListener(v -> {
            showSearchPlacesButton(false);
            adapter.searchPlacesWithQuery(null, userLocation, true, true);
            searchedForCustomLocations = true;
            showResults();
        });
    }
    mapTypeButton = new ActionBarMenuItem(context, null, 0, Theme.getColor(Theme.key_location_actionIcon));
    mapTypeButton.setClickable(true);
    mapTypeButton.setSubMenuOpenSide(2);
    mapTypeButton.setAdditionalXOffset(AndroidUtilities.dp(10));
    mapTypeButton.setAdditionalYOffset(-AndroidUtilities.dp(10));
    mapTypeButton.addSubItem(map_list_menu_osm, R.drawable.msg_map, "Standard OSM");
    mapTypeButton.addSubItem(map_list_menu_wiki, R.drawable.msg_map, "Wikimedia");
    mapTypeButton.addSubItem(map_list_menu_cartodark, R.drawable.msg_map, "Carto Dark");
    mapTypeButton.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
        drawable = combinedDrawable;
    } else {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(mapTypeButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(mapTypeButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        mapTypeButton.setStateListAnimator(animator);
        mapTypeButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
            }
        });
    }
    mapTypeButton.setBackgroundDrawable(drawable);
    mapTypeButton.setIcon(R.drawable.location_type);
    mapViewClip.addView(mapTypeButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12, 12, 0));
    mapTypeButton.setOnClickListener(v -> mapTypeButton.toggleSubMenu());
    mapTypeButton.setDelegate(id -> {
        if (mapView == null) {
            return;
        }
        if (id == map_list_menu_osm) {
            attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
            mapView.setTileSource(TileSourceFactory.MAPNIK);
        } else if (id == map_list_menu_wiki) {
            // Create a custom tile source
            ITileSource tileSource = new XYTileSource("Wikimedia", 0, 19, 256, ".png", new String[] { "https://maps.wikimedia.org/osm-intl/" }, "© OpenStreetMap contributors");
            attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors"));
            mapView.setTileSource(tileSource);
        } else if (id == map_list_menu_cartodark) {
            // Create a custom tile source
            ITileSource tileSource = new XYTileSource("Carto Dark", 0, 20, 256, ".png", new String[] { "https://cartodb-basemaps-a.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-b.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-c.global.ssl.fastly.net/dark_all/", "https://cartodb-basemaps-d.global.ssl.fastly.net/dark_all/" }, "© OpenStreetMap contributors, © CARTO");
            attributionOverlay.setText(Html.fromHtml("© <a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> contributors, © <a href=\"https://carto.com/attributions\">CARTO</a>"));
            mapView.setTileSource(tileSource);
        }
    });
    mapViewClip.addView(getAttributionOverlay(context), LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.BOTTOM, LocaleController.isRTL ? 0 : 4, 0, LocaleController.isRTL ? 4 : 0, 20));
    locationButton = new ImageView(context);
    drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
        drawable = combinedDrawable;
    } else {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(locationButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(locationButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        locationButton.setStateListAnimator(animator);
        locationButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
            }
        });
    }
    locationButton.setBackgroundDrawable(drawable);
    locationButton.setImageResource(R.drawable.location_current);
    locationButton.setScaleType(ImageView.ScaleType.CENTER);
    locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY));
    locationButton.setTag(Theme.key_location_actionActiveIcon);
    locationButton.setContentDescription(LocaleController.getString("AccDescrMyLocation", R.string.AccDescrMyLocation));
    FrameLayout.LayoutParams layoutParams1 = LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 12, 12);
    layoutParams1.bottomMargin += layoutParams.height - padding.top;
    mapViewClip.addView(locationButton, layoutParams1);
    locationButton.setOnClickListener(v -> {
        if (Build.VERSION.SDK_INT >= 23) {
            Activity activity = getParentActivity();
            if (activity != null) {
                if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    showPermissionAlert(false);
                    return;
                }
            }
        }
        if (!checkGpsEnabled()) {
            return;
        }
        if (messageObject != null || chatLocation != null) {
            if (myLocation != null && mapView != null) {
                final IMapController controller = mapView.getController();
                controller.animateTo(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()), mapView.getMaxZoomLevel() - 2, null);
            }
        } else {
            if (myLocation != null && mapView != null) {
                locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionActiveIcon), PorterDuff.Mode.MULTIPLY));
                locationButton.setTag(Theme.key_location_actionActiveIcon);
                adapter.setCustomLocation(null);
                userLocationMoved = false;
                showSearchPlacesButton(false);
                final IMapController controller = mapView.getController();
                controller.animateTo(new GeoPoint(myLocation.getLatitude(), myLocation.getLongitude()));
                if (searchedForCustomLocations) {
                    if (myLocation != null) {
                        adapter.searchPlacesWithQuery(null, myLocation, true, true);
                    }
                    searchedForCustomLocations = false;
                    showResults();
                }
            }
        }
        removeInfoView();
    });
    proximityButton = new ImageView(context);
    drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(40), Theme.getColor(Theme.key_location_actionBackground), Theme.getColor(Theme.key_location_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(40), AndroidUtilities.dp(40));
        drawable = combinedDrawable;
    } else {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(proximityButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(proximityButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        proximityButton.setStateListAnimator(animator);
        proximityButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(40), AndroidUtilities.dp(40));
            }
        });
    }
    proximityButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
    proximityButton.setBackgroundDrawable(drawable);
    proximityButton.setScaleType(ImageView.ScaleType.CENTER);
    proximityButton.setContentDescription(LocaleController.getString("AccDescrLocationNotify", R.string.AccDescrLocationNotify));
    mapViewClip.addView(proximityButton, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 40 : 44, Build.VERSION.SDK_INT >= 21 ? 40 : 44, Gravity.RIGHT | Gravity.TOP, 0, 12 + 50, 12, 0));
    proximityButton.setOnClickListener(v -> {
        if (getParentActivity() == null || myLocation == null || !checkGpsEnabled() || mapView == null) {
            return;
        }
        if (hintView != null) {
            hintView.hide();
        }
        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
        preferences.edit().putInt("proximityhint", 3).commit();
        LocationController.SharingLocationInfo info = getLocationController().getSharingLocationInfo(dialogId);
        if (canUndo) {
            undoView[0].hide(true, 1);
        }
        if (info != null && info.proximityMeters > 0) {
            proximityButton.setImageResource(R.drawable.msg_location_alert);
            if (proximityCircle != null) {
                mapView.getOverlayManager().remove(proximityCircle);
                proximityCircle = null;
            }
            canUndo = true;
            getUndoView().showWithAction(0, UndoView.ACTION_PROXIMITY_REMOVED, 0, null, () -> {
                getLocationController().setProximityLocation(dialogId, 0, true);
                canUndo = false;
            }, () -> {
                proximityButton.setImageResource(R.drawable.msg_location_alert2);
                createCircle(info.proximityMeters);
                canUndo = false;
            });
            return;
        }
        openProximityAlert();
    });
    TLRPC.Chat chat = null;
    if (DialogObject.isChatDialog(dialogId)) {
        chat = getMessagesController().getChat(-dialogId);
    }
    if (messageObject == null || !messageObject.isLiveLocation() || messageObject.isExpiredLiveLocation(getConnectionsManager().getCurrentTime()) || ChatObject.isChannel(chat) && !chat.megagroup) {
        proximityButton.setVisibility(View.GONE);
        proximityButton.setImageResource(R.drawable.msg_location_alert);
    } else {
        LocationController.SharingLocationInfo myInfo = getLocationController().getSharingLocationInfo(dialogId);
        if (myInfo != null && myInfo.proximityMeters > 0) {
            proximityButton.setImageResource(R.drawable.msg_location_alert2);
        } else {
            if (DialogObject.isUserDialog(dialogId) && messageObject.getFromChatId() == getUserConfig().getClientUserId()) {
                proximityButton.setVisibility(View.INVISIBLE);
                proximityButton.setAlpha(0.0f);
                proximityButton.setScaleX(0.4f);
                proximityButton.setScaleY(0.4f);
            }
            proximityButton.setImageResource(R.drawable.msg_location_alert);
        }
    }
    hintView = new HintView(context, 6, true);
    hintView.setVisibility(View.INVISIBLE);
    hintView.setShowingDuration(4000);
    mapViewClip.addView(hintView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0));
    emptyView = new LinearLayout(context);
    emptyView.setOrientation(LinearLayout.VERTICAL);
    emptyView.setGravity(Gravity.CENTER_HORIZONTAL);
    emptyView.setPadding(0, AndroidUtilities.dp(60 + 100), 0, 0);
    emptyView.setVisibility(View.GONE);
    frameLayout.addView(emptyView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    emptyView.setOnTouchListener((v, event) -> true);
    emptyImageView = new ImageView(context);
    emptyImageView.setImageResource(R.drawable.location_empty);
    emptyImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_dialogEmptyImage), PorterDuff.Mode.MULTIPLY));
    emptyView.addView(emptyImageView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
    emptyTitleTextView = new TextView(context);
    emptyTitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText));
    emptyTitleTextView.setGravity(Gravity.CENTER);
    emptyTitleTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    emptyTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    emptyTitleTextView.setText(LocaleController.getString("NoPlacesFound", R.string.NoPlacesFound));
    emptyView.addView(emptyTitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 11, 0, 0));
    emptySubtitleTextView = new TextView(context);
    emptySubtitleTextView.setTextColor(Theme.getColor(Theme.key_dialogEmptyText));
    emptySubtitleTextView.setGravity(Gravity.CENTER);
    emptySubtitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    emptySubtitleTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0);
    emptyView.addView(emptySubtitleTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 6, 0, 0));
    listView = new RecyclerListView(context);
    listView.setAdapter(adapter = new LocationActivityAdapter(context, locationType, dialogId, false, null) {

        @Override
        protected void onDirectionClick() {
            if (Build.VERSION.SDK_INT >= 23) {
                Activity activity = getParentActivity();
                if (activity != null) {
                    if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        showPermissionAlert(true);
                        return;
                    }
                }
            }
            if (myLocation != null) {
                try {
                    Intent intent;
                    if (messageObject != null) {
                        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, "http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", myLocation.getLatitude(), myLocation.getLongitude(), messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long)));
                    } else {
                        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, "http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f", myLocation.getLatitude(), myLocation.getLongitude(), chatLocation.geo_point.lat, chatLocation.geo_point._long)));
                    }
                    getParentActivity().startActivity(intent);
                } catch (Exception e) {
                    FileLog.e(e);
                }
            }
        }
    });
    adapter.setMyLocationDenied(locationDenied);
    adapter.setUpdateRunnable(() -> updateClipView(false));
    listView.setVerticalScrollBarEnabled(false);
    listView.setLayoutManager(layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            scrolling = newState != RecyclerView.SCROLL_STATE_IDLE;
            if (!scrolling && forceUpdate != null) {
                forceUpdate = null;
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            updateClipView(false);
            if (forceUpdate != null) {
                yOffset += dy;
            }
        }
    });
    ((DefaultItemAnimator) listView.getItemAnimator()).setDelayAnimations(false);
    listView.setOnItemClickListener((view, position) -> {
        if (locationType == LOCATION_TYPE_GROUP) {
            if (position == 1) {
                TLRPC.TL_messageMediaVenue venue = (TLRPC.TL_messageMediaVenue) adapter.getItem(position);
                if (venue == null) {
                    return;
                }
                if (dialogId == 0) {
                    delegate.didSelectLocation(venue, LOCATION_TYPE_GROUP, true, 0);
                    finishFragment();
                } else {
                    final AlertDialog[] progressDialog = new AlertDialog[] { new AlertDialog(getParentActivity(), 3) };
                    TLRPC.TL_channels_editLocation req = new TLRPC.TL_channels_editLocation();
                    req.address = venue.address;
                    req.channel = getMessagesController().getInputChannel(-dialogId);
                    req.geo_point = new TLRPC.TL_inputGeoPoint();
                    req.geo_point.lat = venue.geo.lat;
                    req.geo_point._long = venue.geo._long;
                    int requestId = getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                        try {
                            progressDialog[0].dismiss();
                        } catch (Throwable ignore) {
                        }
                        progressDialog[0] = null;
                        delegate.didSelectLocation(venue, LOCATION_TYPE_GROUP, true, 0);
                        finishFragment();
                    }));
                    progressDialog[0].setOnCancelListener(dialog -> getConnectionsManager().cancelRequest(requestId, true));
                    showDialog(progressDialog[0]);
                }
            }
        } else if (locationType == LOCATION_TYPE_GROUP_VIEW) {
            if (mapView != null) {
                final IMapController controller = mapView.getController();
                controller.animateTo(new GeoPoint(chatLocation.geo_point.lat, chatLocation.geo_point._long), mapView.getMaxZoomLevel() - 2, null);
            }
        } else if (position == 1 && messageObject != null && (!messageObject.isLiveLocation() || locationType == LOCATION_TYPE_LIVE_VIEW)) {
            if (mapView != null) {
                final IMapController controller = mapView.getController();
                controller.animateTo(new GeoPoint(messageObject.messageOwner.media.geo.lat, messageObject.messageOwner.media.geo._long), mapView.getMaxZoomLevel() - 2, null);
            }
        } else if (position == 1 && locationType != 2) {
            if (delegate != null && userLocation != null) {
                if (lastPressedMarkerView != null) {
                    lastPressedMarkerView.callOnClick();
                } else {
                    TLRPC.TL_messageMediaGeo location = new TLRPC.TL_messageMediaGeo();
                    location.geo = new TLRPC.TL_geoPoint();
                    location.geo.lat = AndroidUtilities.fixLocationCoord(userLocation.getLatitude());
                    location.geo._long = AndroidUtilities.fixLocationCoord(userLocation.getLongitude());
                    if (parentFragment != null && parentFragment.isInScheduleMode()) {
                        AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
                            delegate.didSelectLocation(location, locationType, notify, scheduleDate);
                            finishFragment();
                        });
                    } else {
                        delegate.didSelectLocation(location, locationType, true, 0);
                        finishFragment();
                    }
                }
            }
        } else if (position == 2 && locationType == 1 || position == 1 && locationType == 2 || position == 3 && locationType == 3) {
            if (getLocationController().isSharingLocation(dialogId)) {
                getLocationController().removeSharingLocation(dialogId);
                finishFragment();
            } else {
                openShareLiveLocation(0);
            }
        } else {
            Object object = adapter.getItem(position);
            if (object instanceof TLRPC.TL_messageMediaVenue) {
                if (parentFragment != null && parentFragment.isInScheduleMode()) {
                    AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
                        delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, notify, scheduleDate);
                        finishFragment();
                    });
                } else {
                    delegate.didSelectLocation((TLRPC.TL_messageMediaVenue) object, locationType, true, 0);
                    finishFragment();
                }
            } else if (object instanceof LiveLocation) {
                LiveLocation liveLocation = (LiveLocation) object;
                final IMapController controller = mapView.getController();
                controller.animateTo(liveLocation.marker.getPosition(), mapView.getMaxZoomLevel() - 2, null);
            }
        }
    });
    adapter.setDelegate(dialogId, this::updatePlacesMarkers);
    adapter.setOverScrollHeight(overScrollHeight);
    frameLayout.addView(mapViewClip, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    mapView = new MapView(context) {

        @Override
        public boolean dispatchTouchEvent(MotionEvent ev) {
            MotionEvent eventToRecycle = null;
            if (yOffset != 0) {
                ev = eventToRecycle = MotionEvent.obtain(ev);
                eventToRecycle.offsetLocation(0, -yOffset / 2);
            }
            boolean result = super.dispatchTouchEvent(ev);
            if (eventToRecycle != null) {
                eventToRecycle.recycle();
            }
            return result;
        }

        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            if (messageObject == null && chatLocation == null) {
                if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                    if (animatorSet != null) {
                        animatorSet.cancel();
                    }
                    animatorSet = new AnimatorSet();
                    animatorSet.setDuration(200);
                    animatorSet.playTogether(ObjectAnimator.ofFloat(markerImageView, View.TRANSLATION_Y, markerTop - AndroidUtilities.dp(10)));
                    animatorSet.start();
                } else if (ev.getAction() == MotionEvent.ACTION_UP) {
                    if (animatorSet != null) {
                        animatorSet.cancel();
                    }
                    yOffset = 0;
                    animatorSet = new AnimatorSet();
                    animatorSet.setDuration(200);
                    animatorSet.playTogether(ObjectAnimator.ofFloat(markerImageView, View.TRANSLATION_Y, markerTop));
                    animatorSet.start();
                    adapter.fetchLocationAddress();
                }
                if (ev.getAction() == MotionEvent.ACTION_MOVE) {
                    if (!userLocationMoved) {
                        locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
                        locationButton.setTag(Theme.key_location_actionIcon);
                        userLocationMoved = true;
                    }
                    if (mapView != null) {
                        if (userLocation != null) {
                            userLocation.setLatitude(mapView.getMapCenter().getLatitude());
                            userLocation.setLongitude(mapView.getMapCenter().getLongitude());
                        }
                    }
                    adapter.setCustomLocation(userLocation);
                }
            }
            return super.onTouchEvent(ev);
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            AndroidUtilities.runOnUIThread(() -> {
                if (moveToBounds != null) {
                    mapView.zoomToBoundingBox(moveToBounds, false, AndroidUtilities.dp(80 + 33));
                    moveToBounds = null;
                }
            });
        }
    };
    AndroidUtilities.runOnUIThread(() -> {
        if (mapView != null && getParentActivity() != null) {
            mapView.setPadding(AndroidUtilities.dp(70), 0, AndroidUtilities.dp(70), AndroidUtilities.dp(10));
            onMapInit();
            mapsInitialized = true;
            if (isActiveThemeDark()) {
            /*currentMapStyleDark = true;
                    MapStyleOptions style = MapStyleOptions.loadRawResourceStyle(ApplicationLoader.applicationContext, R.raw.mapstyle_night);
                    googleMap.setMapStyle(style);
                    */
            // TODO Dark?
            }
            if (onResumeCalled) {
                mapView.onResume();
            }
        }
    });
    if (messageObject == null && chatLocation == null) {
        if (chat != null && locationType == LOCATION_TYPE_GROUP && dialogId != 0) {
            FrameLayout frameLayout1 = new FrameLayout(context);
            frameLayout1.setBackgroundResource(R.drawable.livepin);
            mapViewClip.addView(frameLayout1, LayoutHelper.createFrame(62, 76, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
            BackupImageView backupImageView = new BackupImageView(context);
            backupImageView.setRoundRadius(AndroidUtilities.dp(26));
            backupImageView.setForUserOrChat(chat, new AvatarDrawable(chat));
            frameLayout1.addView(backupImageView, LayoutHelper.createFrame(52, 52, Gravity.LEFT | Gravity.TOP, 5, 5, 0, 0));
            markerImageView = frameLayout1;
            markerImageView.setTag(1);
        }
        if (markerImageView == null) {
            ImageView imageView = new ImageView(context);
            imageView.setImageResource(R.drawable.map_pin2);
            mapViewClip.addView(imageView, LayoutHelper.createFrame(28, 48, Gravity.TOP | Gravity.CENTER_HORIZONTAL));
            markerImageView = imageView;
        }
        searchListView = new RecyclerListView(context);
        searchListView.setVisibility(View.GONE);
        searchListView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        searchAdapter = new LocationActivitySearchAdapter(context) {

            @Override
            public void notifyDataSetChanged() {
                if (searchItem != null) {
                    searchItem.setShowSearchProgress(searchAdapter.isSearching());
                }
                if (emptySubtitleTextView != null) {
                    emptySubtitleTextView.setText(AndroidUtilities.replaceTags(LocaleController.formatString("NoPlacesFoundInfo", R.string.NoPlacesFoundInfo, searchAdapter.getLastSearchString())));
                }
                super.notifyDataSetChanged();
            }
        };
        searchAdapter.setDelegate(0, places -> {
            searchInProgress = false;
            updateEmptyView();
        });
        frameLayout.addView(searchListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
        searchListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING && searching && searchWas) {
                    AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
                }
            }
        });
        searchListView.setOnItemClickListener((view, position) -> {
            TLRPC.TL_messageMediaVenue object = searchAdapter.getItem(position);
            if (object != null && delegate != null) {
                if (parentFragment != null && parentFragment.isInScheduleMode()) {
                    AlertsCreator.createScheduleDatePickerDialog(getParentActivity(), parentFragment.getDialogId(), (notify, scheduleDate) -> {
                        delegate.didSelectLocation(object, locationType, notify, scheduleDate);
                        finishFragment();
                    });
                } else {
                    delegate.didSelectLocation(object, locationType, true, 0);
                    finishFragment();
                }
            }
        });
    } else if (messageObject != null && !messageObject.isLiveLocation() || chatLocation != null) {
        if (chatLocation != null) {
            adapter.setChatLocation(chatLocation);
        } else if (messageObject != null) {
            adapter.setMessageObject(messageObject);
        }
    }
    if (messageObject != null && locationType == LOCATION_TYPE_LIVE_VIEW) {
        adapter.setMessageObject(messageObject);
    }
    for (int a = 0; a < 2; a++) {
        undoView[a] = new UndoView(context);
        undoView[a].setAdditionalTranslationY(AndroidUtilities.dp(10));
        if (Build.VERSION.SDK_INT >= 21) {
            undoView[a].setTranslationZ(AndroidUtilities.dp(5));
        }
        mapViewClip.addView(undoView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    }
    shadow = new View(context) {

        private RectF rect = new RectF();

        @Override
        protected void onDraw(Canvas canvas) {
            shadowDrawable.setBounds(-padding.left, 0, getMeasuredWidth() + padding.right, getMeasuredHeight());
            shadowDrawable.draw(canvas);
            if (locationType == LOCATION_TYPE_SEND || locationType == LOCATION_TYPE_SEND_WITH_LIVE) {
                int w = AndroidUtilities.dp(36);
                int y = padding.top + AndroidUtilities.dp(10);
                rect.set((getMeasuredWidth() - w) / 2, y, (getMeasuredWidth() + w) / 2, y + AndroidUtilities.dp(4));
                int color = Theme.getColor(Theme.key_sheet_scrollUp);
                int alpha = Color.alpha(color);
                Theme.dialogs_onlineCirclePaint.setColor(color);
                canvas.drawRoundRect(rect, AndroidUtilities.dp(2), AndroidUtilities.dp(2), Theme.dialogs_onlineCirclePaint);
            }
        }
    };
    if (Build.VERSION.SDK_INT >= 21) {
        shadow.setTranslationZ(AndroidUtilities.dp(6));
    }
    mapViewClip.addView(shadow, layoutParams);
    if (messageObject == null && chatLocation == null && initialLocation != null) {
        userLocationMoved = true;
        locationButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_location_actionIcon), PorterDuff.Mode.MULTIPLY));
        locationButton.setTag(Theme.key_location_actionIcon);
    }
    frameLayout.addView(actionBar);
    updateEmptyView();
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Arrays(java.util.Arrays) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) LocationController(org.telegram.messenger.LocationController) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) Manifest(android.Manifest) StateListAnimator(android.animation.StateListAnimator) ITileSource(org.osmdroid.tileprovider.tilesource.ITileSource) Shader(android.graphics.Shader) Canvas(android.graphics.Canvas) XYTileSource(org.osmdroid.tileprovider.tilesource.XYTileSource) Configuration(org.osmdroid.config.Configuration) LocationActivitySearchAdapter(org.telegram.ui.Adapters.LocationActivitySearchAdapter) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) ScrollEvent(org.osmdroid.events.ScrollEvent) UndoView(org.telegram.ui.Components.UndoView) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) Polygon(org.osmdroid.views.overlay.Polygon) NotificationCenter(org.telegram.messenger.NotificationCenter) Outline(android.graphics.Outline) LocationActivityAdapter(org.telegram.ui.Adapters.LocationActivityAdapter) Html(android.text.Html) HintView(org.telegram.ui.Components.HintView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) FileLoader(org.telegram.messenger.FileLoader) ZoomEvent(org.osmdroid.events.ZoomEvent) BitmapFactory(android.graphics.BitmapFactory) AlertsCreator(org.telegram.ui.Components.AlertsCreator) ArrayList(java.util.ArrayList) TileSourceFactory(org.osmdroid.tileprovider.tilesource.TileSourceFactory) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) BuildConfig(org.telegram.messenger.BuildConfig) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) SharingLiveLocationCell(org.telegram.ui.Cells.SharingLiveLocationCell) MapView(org.osmdroid.views.MapView) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) LocationCell(org.telegram.ui.Cells.LocationCell) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) EditText(android.widget.EditText) ValueAnimator(android.animation.ValueAnimator) IMyLocationProvider(org.osmdroid.views.overlay.mylocation.IMyLocationProvider) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Rect(android.graphics.Rect) MyLocationNewOverlay(org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) PackageManager(android.content.pm.PackageManager) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) Animator(android.animation.Animator) LinkMovementMethod(android.text.method.LinkMovementMethod) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) SendLocationCell(org.telegram.ui.Cells.SendLocationCell) Locale(java.util.Locale) View(android.view.View) IMapController(org.osmdroid.api.IMapController) RecyclerView(androidx.recyclerview.widget.RecyclerView) Matrix(android.graphics.Matrix) RectF(android.graphics.RectF) BitmapShader(android.graphics.BitmapShader) LocationLoadingCell(org.telegram.ui.Cells.LocationLoadingCell) IGeoPoint(org.osmdroid.api.IGeoPoint) GpsMyLocationProvider(org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider) LocationPoweredCell(org.telegram.ui.Cells.LocationPoweredCell) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) Marker(org.osmdroid.views.overlay.Marker) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) BitmapDrawable(android.graphics.drawable.BitmapDrawable) PorterDuff(android.graphics.PorterDuff) MapPlaceholderDrawable(org.telegram.ui.Components.MapPlaceholderDrawable) ViewGroup(android.view.ViewGroup) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) List(java.util.List) TextView(android.widget.TextView) Location(android.location.Location) ProximitySheet(org.telegram.ui.Components.ProximitySheet) LocationManager(android.location.LocationManager) Context(android.content.Context) Theme(org.telegram.ui.ActionBar.Theme) ViewOutlineProvider(android.view.ViewOutlineProvider) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) GeoPoint(org.osmdroid.util.GeoPoint) SuppressLint(android.annotation.SuppressLint) LocationDirectionCell(org.telegram.ui.Cells.LocationDirectionCell) MapListener(org.osmdroid.events.MapListener) MotionEvent(android.view.MotionEvent) ActionBar(org.telegram.ui.ActionBar.ActionBar) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) Build(android.os.Build) Projection(org.osmdroid.views.Projection) LongSparseArray(androidx.collection.LongSparseArray) DialogObject(org.telegram.messenger.DialogObject) BackupImageView(org.telegram.ui.Components.BackupImageView) Point(android.graphics.Point) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) BoundingBox(org.osmdroid.util.BoundingBox) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) Bitmap(android.graphics.Bitmap) OvershootInterpolator(android.view.animation.OvershootInterpolator) Activity(android.app.Activity) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LocationActivitySearchAdapter(org.telegram.ui.Adapters.LocationActivitySearchAdapter) Activity(android.app.Activity) LocationController(org.telegram.messenger.LocationController) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) MapPlaceholderDrawable(org.telegram.ui.Components.MapPlaceholderDrawable) TLRPC(org.telegram.tgnet.TLRPC) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) IGeoPoint(org.osmdroid.api.IGeoPoint) GeoPoint(org.osmdroid.util.GeoPoint) BackupImageView(org.telegram.ui.Components.BackupImageView) MapView(org.osmdroid.views.MapView) IMapController(org.osmdroid.api.IMapController) TextView(android.widget.TextView) ImageView(android.widget.ImageView) BackupImageView(org.telegram.ui.Components.BackupImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) EditText(android.widget.EditText) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Rect(android.graphics.Rect) Canvas(android.graphics.Canvas) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) MapPlaceholderDrawable(org.telegram.ui.Components.MapPlaceholderDrawable) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) ITileSource(org.osmdroid.tileprovider.tilesource.ITileSource) UserObject(org.telegram.messenger.UserObject) ChatObject(org.telegram.messenger.ChatObject) MessageObject(org.telegram.messenger.MessageObject) DialogObject(org.telegram.messenger.DialogObject) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) StateListAnimator(android.animation.StateListAnimator) LocationActivityAdapter(org.telegram.ui.Adapters.LocationActivityAdapter) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) AnimatorSet(android.animation.AnimatorSet) RecyclerListView(org.telegram.ui.Components.RecyclerListView) XYTileSource(org.osmdroid.tileprovider.tilesource.XYTileSource) UndoView(org.telegram.ui.Components.UndoView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) SharedPreferences(android.content.SharedPreferences) Intent(android.content.Intent) Outline(android.graphics.Outline) ImageView(android.widget.ImageView) UndoView(org.telegram.ui.Components.UndoView) HintView(org.telegram.ui.Components.HintView) MapView(org.osmdroid.views.MapView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) TextView(android.widget.TextView) BackupImageView(org.telegram.ui.Components.BackupImageView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ViewOutlineProvider(android.view.ViewOutlineProvider) Paint(android.graphics.Paint) IGeoPoint(org.osmdroid.api.IGeoPoint) GeoPoint(org.osmdroid.util.GeoPoint) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) HintView(org.telegram.ui.Components.HintView) MotionEvent(android.view.MotionEvent) RectF(android.graphics.RectF) FrameLayout(android.widget.FrameLayout) SuppressLint(android.annotation.SuppressLint) RecyclerView(androidx.recyclerview.widget.RecyclerView) LinearLayout(android.widget.LinearLayout) ImageLocation(org.telegram.messenger.ImageLocation) Location(android.location.Location)

Example 13 with StateListAnimator

use of android.animation.StateListAnimator in project Telegram-FOSS by Telegram-FOSS-Team.

the class FilterUsersActivity method createView.

@Override
public View createView(Context context) {
    searching = false;
    searchWas = false;
    allSpans.clear();
    selectedContacts.clear();
    currentDeletingSpan = null;
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    if (isInclude) {
        actionBar.setTitle(LocaleController.getString("FilterAlwaysShow", R.string.FilterAlwaysShow));
    } else {
        actionBar.setTitle(LocaleController.getString("FilterNeverShow", R.string.FilterNeverShow));
    }
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                onDonePressed(true);
            }
        }
    });
    fragmentView = new ViewGroup(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            setMeasuredDimension(width, height);
            int maxSize;
            if (AndroidUtilities.isTablet() || height > width) {
                maxSize = AndroidUtilities.dp(144);
            } else {
                maxSize = AndroidUtilities.dp(56);
            }
            scrollView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(maxSize, MeasureSpec.AT_MOST));
            listView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height - scrollView.getMeasuredHeight(), MeasureSpec.EXACTLY));
            emptyView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height - scrollView.getMeasuredHeight(), MeasureSpec.EXACTLY));
            if (floatingButton != null) {
                int w = AndroidUtilities.dp(Build.VERSION.SDK_INT >= 21 ? 56 : 60);
                floatingButton.measure(MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(w, MeasureSpec.EXACTLY));
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            scrollView.layout(0, 0, scrollView.getMeasuredWidth(), scrollView.getMeasuredHeight());
            listView.layout(0, scrollView.getMeasuredHeight(), listView.getMeasuredWidth(), scrollView.getMeasuredHeight() + listView.getMeasuredHeight());
            emptyView.layout(0, scrollView.getMeasuredHeight(), emptyView.getMeasuredWidth(), scrollView.getMeasuredHeight() + emptyView.getMeasuredHeight());
            if (floatingButton != null) {
                int l = LocaleController.isRTL ? AndroidUtilities.dp(14) : (right - left) - AndroidUtilities.dp(14) - floatingButton.getMeasuredWidth();
                int t = bottom - top - AndroidUtilities.dp(14) - floatingButton.getMeasuredHeight();
                floatingButton.layout(l, t, l + floatingButton.getMeasuredWidth(), t + floatingButton.getMeasuredHeight());
            }
        }

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == listView || child == emptyView) {
                parentLayout.drawHeaderShadow(canvas, scrollView.getMeasuredHeight());
            }
            return result;
        }
    };
    ViewGroup frameLayout = (ViewGroup) fragmentView;
    scrollView = new ScrollView(context) {

        @Override
        public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
            if (ignoreScrollEvent) {
                ignoreScrollEvent = false;
                return false;
            }
            rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY());
            rectangle.top += fieldY + AndroidUtilities.dp(20);
            rectangle.bottom += fieldY + AndroidUtilities.dp(50);
            return super.requestChildRectangleOnScreen(child, rectangle, immediate);
        }
    };
    scrollView.setVerticalScrollBarEnabled(false);
    AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_windowBackgroundWhite));
    frameLayout.addView(scrollView);
    spansContainer = new SpansContainer(context);
    scrollView.addView(spansContainer, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    spansContainer.setOnClickListener(v -> {
        editText.clearFocus();
        editText.requestFocus();
        AndroidUtilities.showKeyboard(editText);
    });
    editText = new EditTextBoldCursor(context) {

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (currentDeletingSpan != null) {
                currentDeletingSpan.cancelDeleteAnimation();
                currentDeletingSpan = null;
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                if (!AndroidUtilities.showKeyboard(this)) {
                    clearFocus();
                    requestFocus();
                }
            }
            return super.onTouchEvent(event);
        }
    };
    editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    editText.setHintColor(Theme.getColor(Theme.key_groupcreate_hintText));
    editText.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    editText.setCursorColor(Theme.getColor(Theme.key_groupcreate_cursor));
    editText.setCursorWidth(1.5f);
    editText.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
    editText.setSingleLine(true);
    editText.setBackgroundDrawable(null);
    editText.setVerticalScrollBarEnabled(false);
    editText.setHorizontalScrollBarEnabled(false);
    editText.setTextIsSelectable(false);
    editText.setPadding(0, 0, 0, 0);
    editText.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
    editText.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
    spansContainer.addView(editText);
    editText.setHintText(LocaleController.getString("SearchForPeopleAndGroups", R.string.SearchForPeopleAndGroups));
    editText.setCustomSelectionActionModeCallback(new ActionMode.Callback() {

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            return false;
        }
    });
    // editText.setOnEditorActionListener((v, actionId, event) -> actionId == EditorInfo.IME_ACTION_DONE && onDonePressed(true));
    editText.setOnKeyListener(new View.OnKeyListener() {

        private boolean wasEmpty;

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    wasEmpty = editText.length() == 0;
                } else if (event.getAction() == KeyEvent.ACTION_UP && wasEmpty && !allSpans.isEmpty()) {
                    GroupCreateSpan span = allSpans.get(allSpans.size() - 1);
                    spansContainer.removeSpan(span);
                    if (span.getUid() == Integer.MIN_VALUE) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 1) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 2) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 3) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 4) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_BOTS;
                    } else if (span.getUid() == Integer.MIN_VALUE + 5) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
                    } else if (span.getUid() == Integer.MIN_VALUE + 6) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
                    } else if (span.getUid() == Integer.MIN_VALUE + 7) {
                        filterFlags &= ~MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                    }
                    updateHint();
                    checkVisibleRows();
                    return true;
                }
            }
            return false;
        }
    });
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editText.length() != 0) {
                if (!adapter.searching) {
                    searching = true;
                    searchWas = true;
                    adapter.setSearching(true);
                    listView.setFastScrollVisible(false);
                    listView.setVerticalScrollBarEnabled(true);
                    emptyView.setText(LocaleController.getString("NoResult", R.string.NoResult));
                    emptyView.showProgress();
                }
                adapter.searchDialogs(editText.getText().toString());
            } else {
                closeSearch();
            }
        }
    });
    emptyView = new EmptyTextProgressView(context);
    if (ContactsController.getInstance(currentAccount).isLoadingContacts()) {
        emptyView.showProgress();
    } else {
        emptyView.showTextView();
    }
    emptyView.setShowAtCenter(true);
    emptyView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
    frameLayout.addView(emptyView);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
    listView = new RecyclerListView(context);
    listView.setFastScrollEnabled(RecyclerListView.FastScroll.LETTER_TYPE);
    listView.setEmptyView(emptyView);
    listView.setAdapter(adapter = new GroupCreateAdapter(context));
    listView.setLayoutManager(linearLayoutManager);
    listView.setVerticalScrollBarEnabled(false);
    listView.setVerticalScrollbarPosition(LocaleController.isRTL ? View.SCROLLBAR_POSITION_LEFT : View.SCROLLBAR_POSITION_RIGHT);
    listView.addItemDecoration(new ItemDecoration());
    frameLayout.addView(listView);
    listView.setOnItemClickListener((view, position) -> {
        if (view instanceof GroupCreateUserCell) {
            GroupCreateUserCell cell = (GroupCreateUserCell) view;
            Object object = cell.getObject();
            long id;
            if (object instanceof String) {
                int flag;
                if (isInclude) {
                    if (position == 1) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
                        id = Integer.MIN_VALUE;
                    } else if (position == 2) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
                        id = Integer.MIN_VALUE + 1;
                    } else if (position == 3) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
                        id = Integer.MIN_VALUE + 2;
                    } else if (position == 4) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
                        id = Integer.MIN_VALUE + 3;
                    } else {
                        flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
                        id = Integer.MIN_VALUE + 4;
                    }
                } else {
                    if (position == 1) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
                        id = Integer.MIN_VALUE + 5;
                    } else if (position == 2) {
                        flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
                        id = Integer.MIN_VALUE + 6;
                    } else {
                        flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
                        id = Integer.MIN_VALUE + 7;
                    }
                }
                if (cell.isChecked()) {
                    filterFlags &= ~flag;
                } else {
                    filterFlags |= flag;
                }
            } else {
                if (object instanceof TLRPC.User) {
                    id = ((TLRPC.User) object).id;
                } else if (object instanceof TLRPC.Chat) {
                    id = -((TLRPC.Chat) object).id;
                } else {
                    return;
                }
            }
            boolean exists;
            if (exists = selectedContacts.indexOfKey(id) >= 0) {
                GroupCreateSpan span = selectedContacts.get(id);
                spansContainer.removeSpan(span);
            } else {
                if (!(object instanceof String) && selectedCount >= 100) {
                    return;
                }
                if (object instanceof TLRPC.User) {
                    TLRPC.User user = (TLRPC.User) object;
                    MessagesController.getInstance(currentAccount).putUser(user, !searching);
                } else if (object instanceof TLRPC.Chat) {
                    TLRPC.Chat chat = (TLRPC.Chat) object;
                    MessagesController.getInstance(currentAccount).putChat(chat, !searching);
                }
                GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
                spansContainer.addSpan(span, true);
                span.setOnClickListener(FilterUsersActivity.this);
            }
            updateHint();
            if (searching || searchWas) {
                AndroidUtilities.showKeyboard(editText);
            } else {
                cell.setChecked(!exists, true);
            }
            if (editText.length() > 0) {
                editText.setText(null);
            }
        }
    });
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                AndroidUtilities.hideKeyboard(editText);
            }
        }
    });
    floatingButton = new ImageView(context);
    floatingButton.setScaleType(ImageView.ScaleType.CENTER);
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_chats_actionBackground), Theme.getColor(Theme.key_chats_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        drawable = combinedDrawable;
    }
    floatingButton.setBackgroundDrawable(drawable);
    floatingButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_actionIcon), PorterDuff.Mode.MULTIPLY));
    floatingButton.setImageResource(R.drawable.floating_check);
    if (Build.VERSION.SDK_INT >= 21) {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        floatingButton.setStateListAnimator(animator);
        floatingButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            }
        });
    }
    frameLayout.addView(floatingButton);
    floatingButton.setOnClickListener(v -> onDonePressed(true));
    /*floatingButton.setVisibility(View.INVISIBLE);
        floatingButton.setScaleX(0.0f);
        floatingButton.setScaleY(0.0f);
        floatingButton.setAlpha(0.0f);*/
    floatingButton.setContentDescription(LocaleController.getString("Next", R.string.Next));
    for (int position = 1, N = (isInclude ? 5 : 3); position <= N; position++) {
        int id;
        int flag;
        Object object;
        if (isInclude) {
            if (position == 1) {
                object = "contacts";
                flag = MessagesController.DIALOG_FILTER_FLAG_CONTACTS;
            } else if (position == 2) {
                object = "non_contacts";
                flag = MessagesController.DIALOG_FILTER_FLAG_NON_CONTACTS;
            } else if (position == 3) {
                object = "groups";
                flag = MessagesController.DIALOG_FILTER_FLAG_GROUPS;
            } else if (position == 4) {
                object = "channels";
                flag = MessagesController.DIALOG_FILTER_FLAG_CHANNELS;
            } else {
                object = "bots";
                flag = MessagesController.DIALOG_FILTER_FLAG_BOTS;
            }
        } else {
            if (position == 1) {
                object = "muted";
                flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_MUTED;
            } else if (position == 2) {
                object = "read";
                flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_READ;
            } else {
                object = "archived";
                flag = MessagesController.DIALOG_FILTER_FLAG_EXCLUDE_ARCHIVED;
            }
        }
        if ((filterFlags & flag) != 0) {
            GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
            spansContainer.addSpan(span, false);
            span.setOnClickListener(FilterUsersActivity.this);
        }
    }
    if (initialIds != null && !initialIds.isEmpty()) {
        TLObject object;
        for (int a = 0, N = initialIds.size(); a < N; a++) {
            Long id = initialIds.get(a);
            if (id > 0) {
                object = getMessagesController().getUser(id);
            } else {
                object = getMessagesController().getChat(-id);
            }
            if (object == null) {
                continue;
            }
            GroupCreateSpan span = new GroupCreateSpan(editText.getContext(), object);
            spansContainer.addSpan(span, false);
            span.setOnClickListener(FilterUsersActivity.this);
        }
    }
    updateHint();
    return fragmentView;
}
Also used : LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TLRPC(org.telegram.tgnet.TLRPC) ImageView(android.widget.ImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) Rect(android.graphics.Rect) Canvas(android.graphics.Canvas) Drawable(android.graphics.drawable.Drawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) ActionMode(android.view.ActionMode) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) TLObject(org.telegram.tgnet.TLObject) DialogObject(org.telegram.messenger.DialogObject) UserObject(org.telegram.messenger.UserObject) GroupCreateSpan(org.telegram.ui.Components.GroupCreateSpan) StateListAnimator(android.animation.StateListAnimator) GroupCreateUserCell(org.telegram.ui.Cells.GroupCreateUserCell) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) KeyEvent(android.view.KeyEvent) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) Menu(android.view.Menu) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) ViewGroup(android.view.ViewGroup) MenuItem(android.view.MenuItem) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) Outline(android.graphics.Outline) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) ScrollView(android.widget.ScrollView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ViewOutlineProvider(android.view.ViewOutlineProvider) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) ScrollView(android.widget.ScrollView) TLObject(org.telegram.tgnet.TLObject) SuppressLint(android.annotation.SuppressLint) RecyclerView(androidx.recyclerview.widget.RecyclerView)

Example 14 with StateListAnimator

use of android.animation.StateListAnimator in project Telegram-FOSS by Telegram-FOSS-Team.

the class DialogsActivity method createView.

@Override
public View createView(final Context context) {
    searching = false;
    searchWas = false;
    pacmanAnimation = null;
    selectedDialogs.clear();
    maximumVelocity = ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
    AndroidUtilities.runOnUIThread(() -> Theme.createChatResources(context, false));
    ActionBarMenu menu = actionBar.createMenu();
    if (!onlySelect && searchString == null && folderId == 0) {
        doneItem = new ActionBarMenuItem(context, null, Theme.getColor(Theme.key_actionBarDefaultSelector), Theme.getColor(Theme.key_actionBarDefaultIcon), true);
        doneItem.setText(LocaleController.getString("Done", R.string.Done).toUpperCase());
        actionBar.addView(doneItem, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT, 0, 0, 10, 0));
        doneItem.setOnClickListener(v -> {
            filterTabsView.setIsEditing(false);
            showDoneItem(false);
        });
        doneItem.setAlpha(0.0f);
        doneItem.setVisibility(View.GONE);
        proxyDrawable = new ProxyDrawable(context);
        proxyItem = menu.addItem(2, proxyDrawable);
        proxyItem.setContentDescription(LocaleController.getString("ProxySettings", R.string.ProxySettings));
        passcodeDrawable = new RLottieDrawable(R.raw.passcode_lock_close, "passcode_lock_close", AndroidUtilities.dp(28), AndroidUtilities.dp(28), true, null);
        passcodeItem = menu.addItem(1, passcodeDrawable);
        passcodeItem.setContentDescription(LocaleController.getString("AccDescrPasscodeLock", R.string.AccDescrPasscodeLock));
        updatePasscodeButton();
        updateProxyButton(false);
    }
    searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true, true).setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

        @Override
        public void onSearchExpand() {
            searching = true;
            if (switchItem != null) {
                switchItem.setVisibility(View.GONE);
            }
            if (proxyItem != null && proxyItemVisible) {
                proxyItem.setVisibility(View.GONE);
            }
            if (viewPages[0] != null) {
                if (searchString != null) {
                    viewPages[0].listView.hide();
                    if (searchViewPager != null) {
                        searchViewPager.searchListView.show();
                    }
                }
                if (!onlySelect) {
                    floatingButtonContainer.setVisibility(View.GONE);
                }
            }
            setScrollY(0);
            updatePasscodeButton();
            actionBar.setBackButtonContentDescription(LocaleController.getString("AccDescrGoBack", R.string.AccDescrGoBack));
        }

        @Override
        public boolean canCollapseSearch() {
            if (switchItem != null) {
                switchItem.setVisibility(View.VISIBLE);
            }
            if (proxyItem != null && proxyItemVisible) {
                proxyItem.setVisibility(View.VISIBLE);
            }
            if (searchString != null) {
                finishFragment();
                return false;
            }
            return true;
        }

        @Override
        public void onSearchCollapse() {
            searching = false;
            searchWas = false;
            if (viewPages[0] != null) {
                viewPages[0].listView.setEmptyView(folderId == 0 ? viewPages[0].progressView : null);
                if (!onlySelect) {
                    floatingButtonContainer.setVisibility(View.VISIBLE);
                    floatingHidden = true;
                    floatingButtonTranslation = AndroidUtilities.dp(100);
                    floatingButtonHideProgress = 1f;
                    updateFloatingButtonOffset();
                }
                showSearch(false, true);
            }
            updatePasscodeButton();
            if (menuDrawable != null) {
                if (actionBar.getBackButton().getDrawable() != menuDrawable) {
                    actionBar.setBackButtonDrawable(menuDrawable);
                    menuDrawable.setRotation(0, true);
                }
                actionBar.setBackButtonContentDescription(LocaleController.getString("AccDescrOpenMenu", R.string.AccDescrOpenMenu));
            }
        }

        @Override
        public void onTextChanged(EditText editText) {
            String text = editText.getText().toString();
            if (text.length() != 0 || (searchViewPager.dialogsSearchAdapter != null && searchViewPager.dialogsSearchAdapter.hasRecentSearch()) || searchFiltersWasShowed) {
                searchWas = true;
                if (!searchIsShowed) {
                    showSearch(true, true);
                }
            }
            searchViewPager.onTextChanged(text);
        }

        @Override
        public void onSearchFilterCleared(FiltersView.MediaFilterData filterData) {
            if (!searchIsShowed) {
                return;
            }
            searchViewPager.removeSearchFilter(filterData);
            searchViewPager.onTextChanged(searchItem.getSearchField().getText().toString());
            updateFiltersView(true, null, null, false, true);
        }

        @Override
        public boolean canToggleSearch() {
            return !actionBar.isActionModeShowed() && databaseMigrationHint == null;
        }
    });
    searchItem.setSearchFieldHint(LocaleController.getString("Search", R.string.Search));
    searchItem.setContentDescription(LocaleController.getString("Search", R.string.Search));
    if (onlySelect) {
        actionBar.setBackButtonImage(R.drawable.ic_ab_back);
        if (initialDialogsType == 3 && selectAlertString == null) {
            actionBar.setTitle(LocaleController.getString("ForwardTo", R.string.ForwardTo));
        } else if (initialDialogsType == 10) {
            actionBar.setTitle(LocaleController.getString("SelectChats", R.string.SelectChats));
        } else {
            actionBar.setTitle(LocaleController.getString("SelectChat", R.string.SelectChat));
        }
        actionBar.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefault));
    } else {
        if (searchString != null || folderId != 0) {
            actionBar.setBackButtonDrawable(backDrawable = new BackDrawable(false));
        } else {
            actionBar.setBackButtonDrawable(menuDrawable = new MenuDrawable());
            actionBar.setBackButtonContentDescription(LocaleController.getString("AccDescrOpenMenu", R.string.AccDescrOpenMenu));
        }
        if (folderId != 0) {
            actionBar.setTitle(LocaleController.getString("ArchivedChats", R.string.ArchivedChats));
        } else {
            if (BuildVars.DEBUG_VERSION) {
                actionBar.setTitle("Telegram Beta");
            } else {
                actionBar.setTitle(LocaleController.getString("AppName", R.string.AppName));
            }
        }
        if (folderId == 0) {
            actionBar.setSupportsHolidayImage(true);
        }
    }
    if (!onlySelect) {
        actionBar.setAddToContainer(false);
        actionBar.setCastShadows(false);
        actionBar.setClipContent(true);
    }
    actionBar.setTitleActionRunnable(() -> {
        if (initialDialogsType != 10) {
            hideFloatingButton(false);
        }
        scrollToTop();
    });
    if (initialDialogsType == 0 && folderId == 0 && !onlySelect && TextUtils.isEmpty(searchString)) {
        scrimPaint = new Paint() {

            @Override
            public void setAlpha(int a) {
                super.setAlpha(a);
                if (fragmentView != null) {
                    fragmentView.invalidate();
                }
            }
        };
        filterTabsView = new FilterTabsView(context) {

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                getParent().requestDisallowInterceptTouchEvent(true);
                maybeStartTracking = false;
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public void setTranslationY(float translationY) {
                if (getTranslationY() != translationY) {
                    super.setTranslationY(translationY);
                    updateContextViewPosition();
                    if (fragmentView != null) {
                        fragmentView.invalidate();
                    }
                }
            }

            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                super.onLayout(changed, l, t, r, b);
                if (scrimView != null) {
                    scrimView.getLocationInWindow(scrimViewLocation);
                    fragmentView.invalidate();
                }
            }
        };
        filterTabsView.setVisibility(View.GONE);
        canShowFilterTabsView = false;
        filterTabsView.setDelegate(new FilterTabsView.FilterTabsViewDelegate() {

            private void showDeleteAlert(MessagesController.DialogFilter dialogFilter) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("FilterDelete", R.string.FilterDelete));
                builder.setMessage(LocaleController.getString("FilterDeleteAlert", R.string.FilterDeleteAlert));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                builder.setPositiveButton(LocaleController.getString("Delete", R.string.Delete), (dialog2, which2) -> {
                    TLRPC.TL_messages_updateDialogFilter req = new TLRPC.TL_messages_updateDialogFilter();
                    req.id = dialogFilter.id;
                    getConnectionsManager().sendRequest(req, (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    }));
                    // if (getMessagesController().dialogFilters.size() > 1) {
                    // filterTabsView.beginCrossfade();
                    // }
                    getMessagesController().removeFilter(dialogFilter);
                    getMessagesStorage().deleteDialogFilter(dialogFilter);
                // filterTabsView.commitCrossfade();
                });
                AlertDialog alertDialog = builder.create();
                showDialog(alertDialog);
                TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                if (button != null) {
                    button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
                }
            }

            @Override
            public void onSamePageSelected() {
                scrollToTop();
            }

            @Override
            public void onPageReorder(int fromId, int toId) {
                for (int a = 0; a < viewPages.length; a++) {
                    if (viewPages[a].selectedType == fromId) {
                        viewPages[a].selectedType = toId;
                    } else if (viewPages[a].selectedType == toId) {
                        viewPages[a].selectedType = fromId;
                    }
                }
            }

            @Override
            public void onPageSelected(int id, boolean forward) {
                if (viewPages[0].selectedType == id) {
                    return;
                }
                ArrayList<MessagesController.DialogFilter> dialogFilters = getMessagesController().dialogFilters;
                if (id != Integer.MAX_VALUE && (id < 0 || id >= dialogFilters.size())) {
                    return;
                }
                if (parentLayout != null) {
                    parentLayout.getDrawerLayoutContainer().setAllowOpenDrawerBySwipe(id == filterTabsView.getFirstTabId() || SharedConfig.getChatSwipeAction(currentAccount) != SwipeGestureSettingsView.SWIPE_GESTURE_FOLDERS);
                }
                viewPages[1].selectedType = id;
                viewPages[1].setVisibility(View.VISIBLE);
                viewPages[1].setTranslationX(viewPages[0].getMeasuredWidth());
                showScrollbars(false);
                switchToCurrentSelectedMode(true);
                animatingForward = forward;
            }

            @Override
            public boolean canPerformActions() {
                return !searching;
            }

            @Override
            public void onPageScrolled(float progress) {
                if (progress == 1 && viewPages[1].getVisibility() != View.VISIBLE && !searching) {
                    return;
                }
                if (animatingForward) {
                    viewPages[0].setTranslationX(-progress * viewPages[0].getMeasuredWidth());
                    viewPages[1].setTranslationX(viewPages[0].getMeasuredWidth() - progress * viewPages[0].getMeasuredWidth());
                } else {
                    viewPages[0].setTranslationX(progress * viewPages[0].getMeasuredWidth());
                    viewPages[1].setTranslationX(progress * viewPages[0].getMeasuredWidth() - viewPages[0].getMeasuredWidth());
                }
                if (progress == 1) {
                    ViewPage tempPage = viewPages[0];
                    viewPages[0] = viewPages[1];
                    viewPages[1] = tempPage;
                    viewPages[1].setVisibility(View.GONE);
                    showScrollbars(true);
                    updateCounters(false);
                    checkListLoad(viewPages[0]);
                    viewPages[0].dialogsAdapter.resume();
                    viewPages[1].dialogsAdapter.pause();
                }
            }

            @Override
            public int getTabCounter(int tabId) {
                if (tabId == Integer.MAX_VALUE) {
                    return getMessagesStorage().getMainUnreadCount();
                }
                ArrayList<MessagesController.DialogFilter> dialogFilters = getMessagesController().dialogFilters;
                if (tabId < 0 || tabId >= dialogFilters.size()) {
                    return 0;
                }
                return getMessagesController().dialogFilters.get(tabId).unreadCount;
            }

            @Override
            public boolean didSelectTab(FilterTabsView.TabView tabView, boolean selected) {
                if (actionBar.isActionModeShowed()) {
                    return false;
                }
                if (scrimPopupWindow != null) {
                    scrimPopupWindow.dismiss();
                    scrimPopupWindow = null;
                    scrimPopupWindowItems = null;
                    return false;
                }
                Rect rect = new Rect();
                MessagesController.DialogFilter dialogFilter;
                if (tabView.getId() == Integer.MAX_VALUE) {
                    dialogFilter = null;
                } else {
                    dialogFilter = getMessagesController().dialogFilters.get(tabView.getId());
                }
                ActionBarPopupWindow.ActionBarPopupWindowLayout popupLayout = new ActionBarPopupWindow.ActionBarPopupWindowLayout(getParentActivity());
                popupLayout.setOnTouchListener(new View.OnTouchListener() {

                    private int[] pos = new int[2];

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
                            if (scrimPopupWindow != null && scrimPopupWindow.isShowing()) {
                                View contentView = scrimPopupWindow.getContentView();
                                contentView.getLocationInWindow(pos);
                                rect.set(pos[0], pos[1], pos[0] + contentView.getMeasuredWidth(), pos[1] + contentView.getMeasuredHeight());
                                if (!rect.contains((int) event.getX(), (int) event.getY())) {
                                    scrimPopupWindow.dismiss();
                                }
                            }
                        } else if (event.getActionMasked() == MotionEvent.ACTION_OUTSIDE) {
                            if (scrimPopupWindow != null && scrimPopupWindow.isShowing()) {
                                scrimPopupWindow.dismiss();
                            }
                        }
                        return false;
                    }
                });
                popupLayout.setDispatchKeyEventListener(keyEvent -> {
                    if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_BACK && keyEvent.getRepeatCount() == 0 && scrimPopupWindow != null && scrimPopupWindow.isShowing()) {
                        scrimPopupWindow.dismiss();
                    }
                });
                Rect backgroundPaddings = new Rect();
                Drawable shadowDrawable = getParentActivity().getResources().getDrawable(R.drawable.popup_fixed_alert).mutate();
                shadowDrawable.getPadding(backgroundPaddings);
                popupLayout.setBackgroundDrawable(shadowDrawable);
                popupLayout.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultSubmenuBackground));
                LinearLayout linearLayout = new LinearLayout(getParentActivity());
                ScrollView scrollView;
                if (Build.VERSION.SDK_INT >= 21) {
                    scrollView = new ScrollView(getParentActivity(), null, 0, R.style.scrollbarShapeStyle) {

                        @Override
                        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                            setMeasuredDimension(linearLayout.getMeasuredWidth(), getMeasuredHeight());
                        }
                    };
                } else {
                    scrollView = new ScrollView(getParentActivity());
                }
                scrollView.setClipToPadding(false);
                popupLayout.addView(scrollView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));
                linearLayout.setMinimumWidth(AndroidUtilities.dp(200));
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                scrimPopupWindowItems = new ActionBarMenuSubItem[3];
                for (int a = 0, N = (tabView.getId() == Integer.MAX_VALUE ? 2 : 3); a < N; a++) {
                    ActionBarMenuSubItem cell = new ActionBarMenuSubItem(getParentActivity(), a == 0, a == N - 1);
                    if (a == 0) {
                        if (getMessagesController().dialogFilters.size() <= 1) {
                            continue;
                        }
                        cell.setTextAndIcon(LocaleController.getString("FilterReorder", R.string.FilterReorder), R.drawable.tabs_reorder);
                    } else if (a == 1) {
                        if (N == 2) {
                            cell.setTextAndIcon(LocaleController.getString("FilterEditAll", R.string.FilterEditAll), R.drawable.msg_edit);
                        } else {
                            cell.setTextAndIcon(LocaleController.getString("FilterEdit", R.string.FilterEdit), R.drawable.msg_edit);
                        }
                    } else {
                        cell.setTextAndIcon(LocaleController.getString("FilterDeleteItem", R.string.FilterDeleteItem), R.drawable.msg_delete);
                    }
                    scrimPopupWindowItems[a] = cell;
                    linearLayout.addView(cell);
                    final int i = a;
                    cell.setOnClickListener(v1 -> {
                        if (i == 0) {
                            resetScroll();
                            filterTabsView.setIsEditing(true);
                            showDoneItem(true);
                        } else if (i == 1) {
                            if (N == 2) {
                                presentFragment(new FiltersSetupActivity());
                            } else {
                                presentFragment(new FilterCreateActivity(dialogFilter));
                            }
                        } else if (i == 2) {
                            showDeleteAlert(dialogFilter);
                        }
                        if (scrimPopupWindow != null) {
                            scrimPopupWindow.dismiss();
                        }
                    });
                }
                scrollView.addView(linearLayout, LayoutHelper.createScroll(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP));
                scrimPopupWindow = new ActionBarPopupWindow(popupLayout, LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT) {

                    @Override
                    public void dismiss() {
                        super.dismiss();
                        if (scrimPopupWindow != this) {
                            return;
                        }
                        scrimPopupWindow = null;
                        scrimPopupWindowItems = null;
                        if (scrimAnimatorSet != null) {
                            scrimAnimatorSet.cancel();
                            scrimAnimatorSet = null;
                        }
                        scrimAnimatorSet = new AnimatorSet();
                        ArrayList<Animator> animators = new ArrayList<>();
                        animators.add(ObjectAnimator.ofInt(scrimPaint, AnimationProperties.PAINT_ALPHA, 0));
                        scrimAnimatorSet.playTogether(animators);
                        scrimAnimatorSet.setDuration(220);
                        scrimAnimatorSet.addListener(new AnimatorListenerAdapter() {

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (scrimView != null) {
                                    scrimView.setBackground(null);
                                    scrimView = null;
                                }
                                if (fragmentView != null) {
                                    fragmentView.invalidate();
                                }
                            }
                        });
                        scrimAnimatorSet.start();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            getParentActivity().getWindow().getDecorView().setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO);
                        }
                    }
                };
                tabView.setBackground(Theme.createRoundRectDrawable(AndroidUtilities.dp(6), Theme.getColor(Theme.key_actionBarDefault)));
                scrimPopupWindow.setDismissAnimationDuration(220);
                scrimPopupWindow.setOutsideTouchable(true);
                scrimPopupWindow.setClippingEnabled(true);
                scrimPopupWindow.setAnimationStyle(R.style.PopupContextAnimation);
                scrimPopupWindow.setFocusable(true);
                popupLayout.measure(View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1000), View.MeasureSpec.AT_MOST));
                scrimPopupWindow.setInputMethodMode(ActionBarPopupWindow.INPUT_METHOD_NOT_NEEDED);
                scrimPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
                scrimPopupWindow.getContentView().setFocusableInTouchMode(true);
                tabView.getLocationInWindow(scrimViewLocation);
                int popupX = scrimViewLocation[0] + backgroundPaddings.left - AndroidUtilities.dp(16);
                if (popupX < AndroidUtilities.dp(6)) {
                    popupX = AndroidUtilities.dp(6);
                } else if (popupX > fragmentView.getMeasuredWidth() - AndroidUtilities.dp(6) - popupLayout.getMeasuredWidth()) {
                    popupX = fragmentView.getMeasuredWidth() - AndroidUtilities.dp(6) - popupLayout.getMeasuredWidth();
                }
                int popupY = scrimViewLocation[1] + tabView.getMeasuredHeight() - AndroidUtilities.dp(12);
                scrimPopupWindow.showAtLocation(fragmentView, Gravity.LEFT | Gravity.TOP, popupX, popupY);
                scrimView = tabView;
                scrimViewSelected = selected;
                fragmentView.invalidate();
                if (scrimAnimatorSet != null) {
                    scrimAnimatorSet.cancel();
                }
                scrimAnimatorSet = new AnimatorSet();
                ArrayList<Animator> animators = new ArrayList<>();
                animators.add(ObjectAnimator.ofInt(scrimPaint, AnimationProperties.PAINT_ALPHA, 0, 50));
                scrimAnimatorSet.playTogether(animators);
                scrimAnimatorSet.setDuration(150);
                scrimAnimatorSet.start();
                return true;
            }

            @Override
            public boolean isTabMenuVisible() {
                return scrimPopupWindow != null && scrimPopupWindow.isShowing();
            }

            @Override
            public void onDeletePressed(int id) {
                showDeleteAlert(getMessagesController().dialogFilters.get(id));
            }
        });
    }
    if (allowSwitchAccount && UserConfig.getActivatedAccountsCount() > 1) {
        switchItem = menu.addItemWithWidth(1, 0, AndroidUtilities.dp(56));
        AvatarDrawable avatarDrawable = new AvatarDrawable();
        avatarDrawable.setTextSize(AndroidUtilities.dp(12));
        BackupImageView imageView = new BackupImageView(context);
        imageView.setRoundRadius(AndroidUtilities.dp(18));
        switchItem.addView(imageView, LayoutHelper.createFrame(36, 36, Gravity.CENTER));
        TLRPC.User user = getUserConfig().getCurrentUser();
        avatarDrawable.setInfo(user);
        imageView.getImageReceiver().setCurrentAccount(currentAccount);
        imageView.setImage(ImageLocation.getForUserOrChat(user, ImageLocation.TYPE_SMALL), "50_50", ImageLocation.getForUserOrChat(user, ImageLocation.TYPE_STRIPPED), "50_50", avatarDrawable, user);
        for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
            TLRPC.User u = AccountInstance.getInstance(a).getUserConfig().getCurrentUser();
            if (u != null) {
                AccountSelectCell cell = new AccountSelectCell(context, false);
                cell.setAccount(a, true);
                switchItem.addSubItem(10 + a, cell, AndroidUtilities.dp(230), AndroidUtilities.dp(48));
            }
        }
    }
    actionBar.setAllowOverlayTitle(true);
    if (sideMenu != null) {
        sideMenu.setBackgroundColor(Theme.getColor(Theme.key_chats_menuBackground));
        sideMenu.setGlowColor(Theme.getColor(Theme.key_chats_menuBackground));
        sideMenu.getAdapter().notifyDataSetChanged();
    }
    createActionMode(null);
    ContentView contentView = new ContentView(context);
    fragmentView = contentView;
    int pagesCount = folderId == 0 && initialDialogsType == 0 && !onlySelect ? 2 : 1;
    viewPages = new ViewPage[pagesCount];
    for (int a = 0; a < pagesCount; a++) {
        final ViewPage viewPage = new ViewPage(context) {

            @Override
            public void setTranslationX(float translationX) {
                super.setTranslationX(translationX);
                if (tabsAnimationInProgress) {
                    if (viewPages[0] == this) {
                        float scrollProgress = Math.abs(viewPages[0].getTranslationX()) / (float) viewPages[0].getMeasuredWidth();
                        filterTabsView.selectTabWithId(viewPages[1].selectedType, scrollProgress);
                    }
                }
            }
        };
        contentView.addView(viewPage, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        viewPage.dialogsType = initialDialogsType;
        viewPages[a] = viewPage;
        viewPage.progressView = new FlickerLoadingView(context);
        viewPage.progressView.setViewType(FlickerLoadingView.DIALOG_CELL_TYPE);
        viewPage.progressView.setVisibility(View.GONE);
        viewPage.addView(viewPage.progressView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        viewPage.listView = new DialogsRecyclerView(context, viewPage);
        viewPage.listView.setAccessibilityEnabled(false);
        viewPage.listView.setAnimateEmptyView(true, 0);
        viewPage.listView.setClipToPadding(false);
        viewPage.listView.setPivotY(0);
        viewPage.dialogsItemAnimator = new DialogsItemAnimator(viewPage.listView) {

            @Override
            public void onRemoveStarting(RecyclerView.ViewHolder item) {
                super.onRemoveStarting(item);
                if (viewPage.layoutManager.findFirstVisibleItemPosition() == 0) {
                    View v = viewPage.layoutManager.findViewByPosition(0);
                    if (v != null) {
                        v.invalidate();
                    }
                    if (viewPage.archivePullViewState == ARCHIVE_ITEM_STATE_HIDDEN) {
                        viewPage.archivePullViewState = ARCHIVE_ITEM_STATE_SHOWED;
                    }
                    if (viewPage.pullForegroundDrawable != null) {
                        viewPage.pullForegroundDrawable.doNotShow();
                    }
                }
            }

            @Override
            public void onRemoveFinished(RecyclerView.ViewHolder item) {
                if (dialogRemoveFinished == 2) {
                    dialogRemoveFinished = 1;
                }
            }

            @Override
            public void onAddFinished(RecyclerView.ViewHolder item) {
                if (dialogInsertFinished == 2) {
                    dialogInsertFinished = 1;
                }
            }

            @Override
            public void onChangeFinished(RecyclerView.ViewHolder item, boolean oldItem) {
                if (dialogChangeFinished == 2) {
                    dialogChangeFinished = 1;
                }
            }

            @Override
            protected void onAllAnimationsDone() {
                if (dialogRemoveFinished == 1 || dialogInsertFinished == 1 || dialogChangeFinished == 1) {
                    onDialogAnimationFinished();
                }
            }
        };
        // viewPage.listView.setItemAnimator(viewPage.dialogsItemAnimator);
        viewPage.listView.setVerticalScrollBarEnabled(true);
        viewPage.listView.setInstantClick(true);
        viewPage.layoutManager = new LinearLayoutManager(context) {

            private boolean fixOffset;

            @Override
            public void scrollToPositionWithOffset(int position, int offset) {
                if (fixOffset) {
                    offset -= viewPage.listView.getPaddingTop();
                }
                super.scrollToPositionWithOffset(position, offset);
            }

            @Override
            public void prepareForDrop(@NonNull View view, @NonNull View target, int x, int y) {
                fixOffset = true;
                super.prepareForDrop(view, target, x, y);
                fixOffset = false;
            }

            @Override
            public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
                if (hasHiddenArchive() && position == 1) {
                    super.smoothScrollToPosition(recyclerView, state, position);
                } else {
                    LinearSmoothScrollerCustom linearSmoothScroller = new LinearSmoothScrollerCustom(recyclerView.getContext(), LinearSmoothScrollerCustom.POSITION_MIDDLE);
                    linearSmoothScroller.setTargetPosition(position);
                    startSmoothScroll(linearSmoothScroller);
                }
            }

            @Override
            public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
                if (viewPage.listView.fastScrollAnimationRunning) {
                    return 0;
                }
                boolean isDragging = viewPage.listView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING;
                int measuredDy = dy;
                int pTop = viewPage.listView.getPaddingTop();
                if (viewPage.dialogsType == 0 && !onlySelect && folderId == 0 && dy < 0 && getMessagesController().hasHiddenArchive() && viewPage.archivePullViewState == ARCHIVE_ITEM_STATE_HIDDEN) {
                    viewPage.listView.setOverScrollMode(View.OVER_SCROLL_ALWAYS);
                    int currentPosition = viewPage.layoutManager.findFirstVisibleItemPosition();
                    if (currentPosition == 0) {
                        View view = viewPage.layoutManager.findViewByPosition(currentPosition);
                        if (view != null && (view.getBottom() - pTop) <= AndroidUtilities.dp(1)) {
                            currentPosition = 1;
                        }
                    }
                    if (!isDragging) {
                        View view = viewPage.layoutManager.findViewByPosition(currentPosition);
                        if (view != null) {
                            int dialogHeight = AndroidUtilities.dp(SharedConfig.useThreeLinesLayout ? 78 : 72) + 1;
                            int canScrollDy = -(view.getTop() - pTop) + (currentPosition - 1) * dialogHeight;
                            int positiveDy = Math.abs(dy);
                            if (canScrollDy < positiveDy) {
                                measuredDy = -canScrollDy;
                            }
                        }
                    } else if (currentPosition == 0) {
                        View v = viewPage.layoutManager.findViewByPosition(currentPosition);
                        float k = 1f + ((v.getTop() - pTop) / (float) v.getMeasuredHeight());
                        if (k > 1f) {
                            k = 1f;
                        }
                        viewPage.listView.setOverScrollMode(View.OVER_SCROLL_NEVER);
                        measuredDy *= PullForegroundDrawable.startPullParallax - PullForegroundDrawable.endPullParallax * k;
                        if (measuredDy > -1) {
                            measuredDy = -1;
                        }
                        if (undoView[0].getVisibility() == View.VISIBLE) {
                            undoView[0].hide(true, 1);
                        }
                    }
                }
                if (viewPage.dialogsType == 0 && viewPage.listView.getViewOffset() != 0 && dy > 0 && isDragging) {
                    float ty = (int) viewPage.listView.getViewOffset();
                    ty -= dy;
                    if (ty < 0) {
                        measuredDy = (int) ty;
                        ty = 0;
                    } else {
                        measuredDy = 0;
                    }
                    viewPage.listView.setViewsOffset(ty);
                }
                if (viewPage.dialogsType == 0 && viewPage.archivePullViewState != ARCHIVE_ITEM_STATE_PINNED && hasHiddenArchive()) {
                    int usedDy = super.scrollVerticallyBy(measuredDy, recycler, state);
                    if (viewPage.pullForegroundDrawable != null) {
                        viewPage.pullForegroundDrawable.scrollDy = usedDy;
                    }
                    int currentPosition = viewPage.layoutManager.findFirstVisibleItemPosition();
                    View firstView = null;
                    if (currentPosition == 0) {
                        firstView = viewPage.layoutManager.findViewByPosition(currentPosition);
                    }
                    if (currentPosition == 0 && firstView != null && (firstView.getBottom() - pTop) >= AndroidUtilities.dp(4)) {
                        if (startArchivePullingTime == 0) {
                            startArchivePullingTime = System.currentTimeMillis();
                        }
                        if (viewPage.archivePullViewState == ARCHIVE_ITEM_STATE_HIDDEN) {
                            if (viewPage.pullForegroundDrawable != null) {
                                viewPage.pullForegroundDrawable.showHidden();
                            }
                        }
                        float k = 1f + ((firstView.getTop() - pTop) / (float) firstView.getMeasuredHeight());
                        if (k > 1f) {
                            k = 1f;
                        }
                        long pullingTime = System.currentTimeMillis() - startArchivePullingTime;
                        boolean canShowInternal = k > PullForegroundDrawable.SNAP_HEIGHT && pullingTime > PullForegroundDrawable.minPullingTime + 20;
                        if (canShowHiddenArchive != canShowInternal) {
                            canShowHiddenArchive = canShowInternal;
                            if (viewPage.archivePullViewState == ARCHIVE_ITEM_STATE_HIDDEN) {
                                viewPage.listView.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
                                if (viewPage.pullForegroundDrawable != null) {
                                    viewPage.pullForegroundDrawable.colorize(canShowInternal);
                                }
                            }
                        }
                        if (viewPage.archivePullViewState == ARCHIVE_ITEM_STATE_HIDDEN && measuredDy - usedDy != 0 && dy < 0 && isDragging) {
                            float ty;
                            float tk = (viewPage.listView.getViewOffset() / PullForegroundDrawable.getMaxOverscroll());
                            tk = 1f - tk;
                            ty = (viewPage.listView.getViewOffset() - dy * PullForegroundDrawable.startPullOverScroll * tk);
                            viewPage.listView.setViewsOffset(ty);
                        }
                        if (viewPage.pullForegroundDrawable != null) {
                            viewPage.pullForegroundDrawable.pullProgress = k;
                            viewPage.pullForegroundDrawable.setListView(viewPage.listView);
                        }
                    } else {
                        startArchivePullingTime = 0;
                        canShowHiddenArchive = false;
                        viewPage.archivePullViewState = ARCHIVE_ITEM_STATE_HIDDEN;
                        if (viewPage.pullForegroundDrawable != null) {
                            viewPage.pullForegroundDrawable.resetText();
                            viewPage.pullForegroundDrawable.pullProgress = 0f;
                            viewPage.pullForegroundDrawable.setListView(viewPage.listView);
                        }
                    }
                    if (firstView != null) {
                        firstView.invalidate();
                    }
                    return usedDy;
                }
                return super.scrollVerticallyBy(measuredDy, recycler, state);
            }

            @Override
            public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
                if (BuildVars.DEBUG_PRIVATE_VERSION) {
                    try {
                        super.onLayoutChildren(recycler, state);
                    } catch (IndexOutOfBoundsException e) {
                        throw new RuntimeException("Inconsistency detected. " + "dialogsListIsFrozen=" + dialogsListFrozen + " lastUpdateAction=" + debugLastUpdateAction);
                    }
                } else {
                    try {
                        super.onLayoutChildren(recycler, state);
                    } catch (IndexOutOfBoundsException e) {
                        FileLog.e(e);
                        AndroidUtilities.runOnUIThread(() -> viewPage.dialogsAdapter.notifyDataSetChanged());
                    }
                }
            }
        };
        viewPage.layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        viewPage.listView.setLayoutManager(viewPage.layoutManager);
        viewPage.listView.setVerticalScrollbarPosition(LocaleController.isRTL ? RecyclerListView.SCROLLBAR_POSITION_LEFT : RecyclerListView.SCROLLBAR_POSITION_RIGHT);
        viewPage.addView(viewPage.listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        viewPage.listView.setOnItemClickListener((view, position) -> {
            if (initialDialogsType == 10) {
                onItemLongClick(view, position, 0, 0, viewPage.dialogsType, viewPage.dialogsAdapter);
                return;
            } else if ((initialDialogsType == 11 || initialDialogsType == 13) && position == 1) {
                Bundle args = new Bundle();
                args.putBoolean("forImport", true);
                long[] array = new long[] { getUserConfig().getClientUserId() };
                args.putLongArray("result", array);
                args.putInt("chatType", ChatObject.CHAT_TYPE_MEGAGROUP);
                String title = arguments.getString("importTitle");
                if (title != null) {
                    args.putString("title", title);
                }
                GroupCreateFinalActivity activity = new GroupCreateFinalActivity(args);
                activity.setDelegate(new GroupCreateFinalActivity.GroupCreateFinalActivityDelegate() {

                    @Override
                    public void didStartChatCreation() {
                    }

                    @Override
                    public void didFinishChatCreation(GroupCreateFinalActivity fragment, long chatId) {
                        ArrayList<Long> arrayList = new ArrayList<>();
                        arrayList.add(-chatId);
                        DialogsActivityDelegate dialogsActivityDelegate = delegate;
                        removeSelfFromStack();
                        dialogsActivityDelegate.didSelectDialogs(DialogsActivity.this, arrayList, null, true);
                    }

                    @Override
                    public void didFailChatCreation() {
                    }
                });
                presentFragment(activity);
                return;
            }
            onItemClick(view, position, viewPage.dialogsAdapter);
        });
        viewPage.listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListenerExtended() {

            @Override
            public boolean onItemClick(View view, int position, float x, float y) {
                if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE && filterTabsView.isEditing()) {
                    return false;
                }
                return onItemLongClick(view, position, x, y, viewPage.dialogsType, viewPage.dialogsAdapter);
            }

            @Override
            public void onLongClickRelease() {
                finishPreviewFragment();
            }

            @Override
            public void onMove(float dx, float dy) {
                movePreviewFragment(dy);
            }
        });
        viewPage.swipeController = new SwipeController(viewPage);
        viewPage.recyclerItemsEnterAnimator = new RecyclerItemsEnterAnimator(viewPage.listView, false);
        viewPage.itemTouchhelper = new ItemTouchHelper(viewPage.swipeController);
        viewPage.itemTouchhelper.attachToRecyclerView(viewPage.listView);
        viewPage.listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            private boolean wasManualScroll;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    wasManualScroll = true;
                    scrollingManually = true;
                } else {
                    scrollingManually = false;
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    wasManualScroll = false;
                    disableActionBarScrolling = false;
                    if (waitingForScrollFinished) {
                        waitingForScrollFinished = false;
                        if (updatePullAfterScroll) {
                            viewPage.listView.updatePullState();
                            updatePullAfterScroll = false;
                        }
                        viewPage.dialogsAdapter.notifyDataSetChanged();
                    }
                    if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE && viewPages[0].listView == recyclerView) {
                        int scrollY = (int) -actionBar.getTranslationY();
                        int actionBarHeight = ActionBar.getCurrentActionBarHeight();
                        if (scrollY != 0 && scrollY != actionBarHeight) {
                            if (scrollY < actionBarHeight / 2) {
                                recyclerView.smoothScrollBy(0, -scrollY);
                            } else if (viewPages[0].listView.canScrollVertically(1)) {
                                recyclerView.smoothScrollBy(0, actionBarHeight - scrollY);
                            }
                        }
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                viewPage.dialogsItemAnimator.onListScroll(-dy);
                checkListLoad(viewPage);
                if (initialDialogsType != 10 && wasManualScroll && floatingButtonContainer.getVisibility() != View.GONE && recyclerView.getChildCount() > 0) {
                    int firstVisibleItem = viewPage.layoutManager.findFirstVisibleItemPosition();
                    if (firstVisibleItem != RecyclerView.NO_POSITION) {
                        RecyclerView.ViewHolder holder = recyclerView.findViewHolderForAdapterPosition(firstVisibleItem);
                        if (!hasHiddenArchive() || holder != null && holder.getAdapterPosition() != 0) {
                            int firstViewTop = 0;
                            if (holder != null) {
                                firstViewTop = holder.itemView.getTop();
                            }
                            boolean goingDown;
                            boolean changed = true;
                            if (prevPosition == firstVisibleItem) {
                                final int topDelta = prevTop - firstViewTop;
                                goingDown = firstViewTop < prevTop;
                                changed = Math.abs(topDelta) > 1;
                            } else {
                                goingDown = firstVisibleItem > prevPosition;
                            }
                            if (changed && scrollUpdated && (goingDown || scrollingManually)) {
                                hideFloatingButton(goingDown);
                            }
                            prevPosition = firstVisibleItem;
                            prevTop = firstViewTop;
                            scrollUpdated = true;
                        }
                    }
                }
                if (filterTabsView != null && filterTabsView.getVisibility() == View.VISIBLE && recyclerView == viewPages[0].listView && !searching && !actionBar.isActionModeShowed() && !disableActionBarScrolling && filterTabsViewIsVisible) {
                    if (dy > 0 && hasHiddenArchive() && viewPages[0].dialogsType == 0) {
                        View child = recyclerView.getChildAt(0);
                        if (child != null) {
                            RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(child);
                            if (holder.getAdapterPosition() == 0) {
                                int visiblePartAfterScroll = child.getMeasuredHeight() + (child.getTop() - recyclerView.getPaddingTop());
                                if (visiblePartAfterScroll + dy > 0) {
                                    if (visiblePartAfterScroll < 0) {
                                        dy = -visiblePartAfterScroll;
                                    } else {
                                        return;
                                    }
                                }
                            }
                        }
                    }
                    float currentTranslation = actionBar.getTranslationY();
                    float newTranslation = currentTranslation - dy;
                    if (newTranslation < -ActionBar.getCurrentActionBarHeight()) {
                        newTranslation = -ActionBar.getCurrentActionBarHeight();
                    } else if (newTranslation > 0) {
                        newTranslation = 0;
                    }
                    if (newTranslation != currentTranslation) {
                        setScrollY(newTranslation);
                    }
                }
            }
        });
        viewPage.archivePullViewState = SharedConfig.archiveHidden ? ARCHIVE_ITEM_STATE_HIDDEN : ARCHIVE_ITEM_STATE_PINNED;
        if (viewPage.pullForegroundDrawable == null && folderId == 0) {
            viewPage.pullForegroundDrawable = new PullForegroundDrawable(LocaleController.getString("AccSwipeForArchive", R.string.AccSwipeForArchive), LocaleController.getString("AccReleaseForArchive", R.string.AccReleaseForArchive)) {

                @Override
                protected float getViewOffset() {
                    return viewPage.listView.getViewOffset();
                }
            };
            if (hasHiddenArchive()) {
                viewPage.pullForegroundDrawable.showHidden();
            } else {
                viewPage.pullForegroundDrawable.doNotShow();
            }
            viewPage.pullForegroundDrawable.setWillDraw(viewPage.archivePullViewState != ARCHIVE_ITEM_STATE_PINNED);
        }
        viewPage.dialogsAdapter = new DialogsAdapter(this, context, viewPage.dialogsType, folderId, onlySelect, selectedDialogs, currentAccount) {

            @Override
            public void notifyDataSetChanged() {
                viewPage.lastItemsCount = getItemCount();
                try {
                    super.notifyDataSetChanged();
                } catch (Exception e) {
                    FileLog.e(e);
                }
            }
        };
        viewPage.dialogsAdapter.setForceShowEmptyCell(afterSignup);
        if (AndroidUtilities.isTablet() && openedDialogId != 0) {
            viewPage.dialogsAdapter.setOpenedDialogId(openedDialogId);
        }
        viewPage.dialogsAdapter.setArchivedPullDrawable(viewPage.pullForegroundDrawable);
        viewPage.listView.setAdapter(viewPage.dialogsAdapter);
        viewPage.listView.setEmptyView(folderId == 0 ? viewPage.progressView : null);
        viewPage.scrollHelper = new RecyclerAnimationScrollHelper(viewPage.listView, viewPage.layoutManager);
        if (a != 0) {
            viewPages[a].setVisibility(View.GONE);
        }
    }
    int type = 0;
    if (searchString != null) {
        type = 2;
    } else if (!onlySelect) {
        type = 1;
    }
    searchViewPager = new SearchViewPager(context, this, type, initialDialogsType, folderId, new SearchViewPager.ChatPreviewDelegate() {

        @Override
        public void startChatPreview(DialogCell cell) {
            showChatPreview(cell);
        }

        @Override
        public void move(float dy) {
            movePreviewFragment(dy);
        }

        @Override
        public void finish() {
            finishPreviewFragment();
        }
    });
    contentView.addView(searchViewPager);
    searchViewPager.dialogsSearchAdapter.setDelegate(new DialogsSearchAdapter.DialogsSearchAdapterDelegate() {

        @Override
        public void searchStateChanged(boolean search, boolean animated) {
            if (searchViewPager.emptyView.getVisibility() == View.VISIBLE) {
                animated = true;
            }
            if (searching && searchWas && searchViewPager.emptyView != null) {
                if (search || searchViewPager.dialogsSearchAdapter.getItemCount() != 0) {
                    searchViewPager.emptyView.showProgress(true, animated);
                } else {
                    searchViewPager.emptyView.showProgress(false, animated);
                }
            }
            if (search && searchViewPager.dialogsSearchAdapter.getItemCount() == 0) {
                searchViewPager.cancelEnterAnimation();
            }
        }

        @Override
        public void didPressedOnSubDialog(long did) {
            if (onlySelect) {
                if (!validateSlowModeDialog(did)) {
                    return;
                }
                if (!selectedDialogs.isEmpty()) {
                    boolean checked = addOrRemoveSelectedDialog(did, null);
                    findAndUpdateCheckBox(did, checked);
                    updateSelectedCount();
                    actionBar.closeSearchField();
                } else {
                    didSelectResult(did, true, false);
                }
            } else {
                Bundle args = new Bundle();
                if (DialogObject.isUserDialog(did)) {
                    args.putLong("user_id", did);
                } else {
                    args.putLong("chat_id", -did);
                }
                closeSearch();
                if (AndroidUtilities.isTablet() && viewPages != null) {
                    for (int a = 0; a < viewPages.length; a++) {
                        viewPages[a].dialogsAdapter.setOpenedDialogId(openedDialogId = did);
                    }
                    updateVisibleRows(MessagesController.UPDATE_MASK_SELECT_DIALOG);
                }
                if (searchString != null) {
                    if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) {
                        getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
                        presentFragment(new ChatActivity(args));
                    }
                } else {
                    if (getMessagesController().checkCanOpenChat(args, DialogsActivity.this)) {
                        presentFragment(new ChatActivity(args));
                    }
                }
            }
        }

        @Override
        public void needRemoveHint(long did) {
            if (getParentActivity() == null) {
                return;
            }
            TLRPC.User user = getMessagesController().getUser(did);
            if (user == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("ChatHintsDeleteAlertTitle", R.string.ChatHintsDeleteAlertTitle));
            builder.setMessage(AndroidUtilities.replaceTags(LocaleController.formatString("ChatHintsDeleteAlert", R.string.ChatHintsDeleteAlert, ContactsController.formatName(user.first_name, user.last_name))));
            builder.setPositiveButton(LocaleController.getString("StickersRemove", R.string.StickersRemove), (dialogInterface, i) -> getMediaDataController().removePeer(did));
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            AlertDialog dialog = builder.create();
            showDialog(dialog);
            TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            if (button != null) {
                button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
            }
        }

        @Override
        public void needClearList() {
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("ClearSearchAlertTitle", R.string.ClearSearchAlertTitle));
            builder.setMessage(LocaleController.getString("ClearSearchAlert", R.string.ClearSearchAlert));
            builder.setPositiveButton(LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(), (dialogInterface, i) -> {
                if (searchViewPager.dialogsSearchAdapter.isRecentSearchDisplayed()) {
                    searchViewPager.dialogsSearchAdapter.clearRecentSearch();
                } else {
                    searchViewPager.dialogsSearchAdapter.clearRecentHashtags();
                }
            });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            AlertDialog dialog = builder.create();
            showDialog(dialog);
            TextView button = (TextView) dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            if (button != null) {
                button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
            }
        }

        @Override
        public void runResultsEnterAnimation() {
            if (searchViewPager != null) {
                searchViewPager.runResultsEnterAnimation();
            }
        }

        @Override
        public boolean isSelected(long dialogId) {
            return selectedDialogs.contains(dialogId);
        }
    });
    searchViewPager.searchListView.setOnItemClickListener((view, position) -> {
        if (initialDialogsType == 10) {
            onItemLongClick(view, position, 0, 0, -1, searchViewPager.dialogsSearchAdapter);
            return;
        }
        onItemClick(view, position, searchViewPager.dialogsSearchAdapter);
    });
    searchViewPager.searchListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListenerExtended() {

        @Override
        public boolean onItemClick(View view, int position, float x, float y) {
            return onItemLongClick(view, position, x, y, -1, searchViewPager.dialogsSearchAdapter);
        }

        @Override
        public void onLongClickRelease() {
            finishPreviewFragment();
        }

        @Override
        public void onMove(float dx, float dy) {
            movePreviewFragment(dy);
        }
    });
    searchViewPager.setFilteredSearchViewDelegate((showMediaFilters, users, dates, archive) -> DialogsActivity.this.updateFiltersView(showMediaFilters, users, dates, archive, true));
    searchViewPager.setVisibility(View.GONE);
    filtersView = new FiltersView(getParentActivity(), null);
    filtersView.setOnItemClickListener((view, position) -> {
        filtersView.cancelClickRunnables(true);
        addSearchFilter(filtersView.getFilterAt(position));
    });
    contentView.addView(filtersView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.TOP));
    filtersView.setVisibility(View.GONE);
    floatingButtonContainer = new FrameLayout(context);
    floatingButtonContainer.setVisibility(onlySelect && initialDialogsType != 10 || folderId != 0 ? View.GONE : View.VISIBLE);
    contentView.addView(floatingButtonContainer, LayoutHelper.createFrame((Build.VERSION.SDK_INT >= 21 ? 56 : 60) + 20, (Build.VERSION.SDK_INT >= 21 ? 56 : 60) + 20, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM, LocaleController.isRTL ? 4 : 0, 0, LocaleController.isRTL ? 0 : 4, 0));
    floatingButtonContainer.setOnClickListener(v -> {
        if (initialDialogsType == 10) {
            if (delegate == null || selectedDialogs.isEmpty()) {
                return;
            }
            delegate.didSelectDialogs(DialogsActivity.this, selectedDialogs, null, false);
        } else {
            Bundle args = new Bundle();
            args.putBoolean("destroyAfterSelect", true);
            presentFragment(new ContactsActivity(args));
        }
    });
    floatingButton = new RLottieImageView(context);
    floatingButton.setScaleType(ImageView.ScaleType.CENTER);
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_chats_actionBackground), Theme.getColor(Theme.key_chats_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        drawable = combinedDrawable;
    }
    floatingButton.setBackgroundDrawable(drawable);
    floatingButton.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_actionIcon), PorterDuff.Mode.MULTIPLY));
    if (initialDialogsType == 10) {
        floatingButton.setImageResource(R.drawable.floating_check);
        floatingButtonContainer.setContentDescription(LocaleController.getString("Done", R.string.Done));
    } else {
        floatingButton.setAnimation(R.raw.write_contacts_fab_icon, 52, 52);
        floatingButtonContainer.setContentDescription(LocaleController.getString("NewMessageTitle", R.string.NewMessageTitle));
    }
    if (Build.VERSION.SDK_INT >= 21) {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(floatingButton, View.TRANSLATION_Z, AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        floatingButton.setStateListAnimator(animator);
        floatingButton.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            }
        });
    }
    floatingButtonContainer.addView(floatingButton, LayoutHelper.createFrame((Build.VERSION.SDK_INT >= 21 ? 56 : 60), (Build.VERSION.SDK_INT >= 21 ? 56 : 60), Gravity.LEFT | Gravity.TOP, 10, 6, 10, 0));
    searchTabsView = null;
    if (!onlySelect && initialDialogsType == 0) {
        fragmentLocationContextView = new FragmentContextView(context, this, true);
        fragmentLocationContextView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
        contentView.addView(fragmentLocationContextView);
        fragmentContextView = new FragmentContextView(context, this, false) {

            @Override
            protected void playbackSpeedChanged(float value) {
                if (Math.abs(value - 1.0f) > 0.001f || Math.abs(value - 1.8f) > 0.001f) {
                    getUndoView().showWithAction(0, Math.abs(value - 1.0f) > 0.001f ? UndoView.ACTION_PLAYBACK_SPEED_ENABLED : UndoView.ACTION_PLAYBACK_SPEED_DISABLED, value, null, null);
                }
            }
        };
        fragmentContextView.setLayoutParams(LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 38, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
        contentView.addView(fragmentContextView);
        fragmentContextView.setAdditionalContextView(fragmentLocationContextView);
        fragmentLocationContextView.setAdditionalContextView(fragmentContextView);
    } else if (initialDialogsType == 3) {
        if (commentView != null) {
            commentView.onDestroy();
        }
        commentView = new ChatActivityEnterView(getParentActivity(), contentView, null, false) {

            @Override
            public boolean dispatchTouchEvent(MotionEvent ev) {
                if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                    AndroidUtilities.requestAdjustResize(getParentActivity(), classGuid);
                }
                return super.dispatchTouchEvent(ev);
            }
        };
        commentView.setAllowStickersAndGifs(false, false);
        commentView.setForceShowSendButton(true, false);
        commentView.setVisibility(View.GONE);
        commentView.getSendButton().setAlpha(0);
        contentView.addView(commentView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
        commentView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {

            @Override
            public void onMessageSend(CharSequence message, boolean notify, int scheduleDate) {
                if (delegate == null || selectedDialogs.isEmpty()) {
                    return;
                }
                delegate.didSelectDialogs(DialogsActivity.this, selectedDialogs, message, false);
            }

            @Override
            public void onSwitchRecordMode(boolean video) {
            }

            @Override
            public void onTextSelectionChanged(int start, int end) {
            }

            @Override
            public void onStickersExpandedChange() {
            }

            @Override
            public void onPreAudioVideoRecord() {
            }

            @Override
            public void onTextChanged(final CharSequence text, boolean bigChange) {
            }

            @Override
            public void onTextSpansChanged(CharSequence text) {
            }

            @Override
            public void needSendTyping() {
            }

            @Override
            public void onAttachButtonHidden() {
            }

            @Override
            public void onAttachButtonShow() {
            }

            @Override
            public void onMessageEditEnd(boolean loading) {
            }

            @Override
            public void onWindowSizeChanged(int size) {
            }

            @Override
            public void onStickersTab(boolean opened) {
            }

            @Override
            public void didPressAttachButton() {
            }

            @Override
            public void needStartRecordVideo(int state, boolean notify, int scheduleDate) {
            }

            @Override
            public void needChangeVideoPreviewState(int state, float seekProgress) {
            }

            @Override
            public void needStartRecordAudio(int state) {
            }

            @Override
            public void needShowMediaBanHint() {
            }

            @Override
            public void onUpdateSlowModeButton(View button, boolean show, CharSequence time) {
            }

            @Override
            public void onSendLongClick() {
            }

            @Override
            public void onAudioVideoInterfaceUpdated() {
            }
        });
        writeButtonContainer = new FrameLayout(context) {

            @Override
            public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
                super.onInitializeAccessibilityNodeInfo(info);
                info.setText(LocaleController.formatPluralString("AccDescrShareInChats", selectedDialogs.size()));
                info.setClassName(Button.class.getName());
                info.setLongClickable(true);
                info.setClickable(true);
            }
        };
        writeButtonContainer.setFocusable(true);
        writeButtonContainer.setFocusableInTouchMode(true);
        writeButtonContainer.setVisibility(View.INVISIBLE);
        writeButtonContainer.setScaleX(0.2f);
        writeButtonContainer.setScaleY(0.2f);
        writeButtonContainer.setAlpha(0.0f);
        contentView.addView(writeButtonContainer, LayoutHelper.createFrame(60, 60, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 6, 10));
        textPaint.setTextSize(AndroidUtilities.dp(12));
        textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        selectedCountView = new View(context) {

            @Override
            protected void onDraw(Canvas canvas) {
                String text = String.format("%d", Math.max(1, selectedDialogs.size()));
                int textSize = (int) Math.ceil(textPaint.measureText(text));
                int size = Math.max(AndroidUtilities.dp(16) + textSize, AndroidUtilities.dp(24));
                int cx = getMeasuredWidth() / 2;
                int cy = getMeasuredHeight() / 2;
                textPaint.setColor(getThemedColor(Theme.key_dialogRoundCheckBoxCheck));
                paint.setColor(getThemedColor(Theme.isCurrentThemeDark() ? Theme.key_voipgroup_inviteMembersBackground : Theme.key_dialogBackground));
                rect.set(cx - size / 2, 0, cx + size / 2, getMeasuredHeight());
                canvas.drawRoundRect(rect, AndroidUtilities.dp(12), AndroidUtilities.dp(12), paint);
                paint.setColor(getThemedColor(Theme.key_dialogRoundCheckBox));
                rect.set(cx - size / 2 + AndroidUtilities.dp(2), AndroidUtilities.dp(2), cx + size / 2 - AndroidUtilities.dp(2), getMeasuredHeight() - AndroidUtilities.dp(2));
                canvas.drawRoundRect(rect, AndroidUtilities.dp(10), AndroidUtilities.dp(10), paint);
                canvas.drawText(text, cx - textSize / 2, AndroidUtilities.dp(16.2f), textPaint);
            }
        };
        selectedCountView.setAlpha(0.0f);
        selectedCountView.setScaleX(0.2f);
        selectedCountView.setScaleY(0.2f);
        contentView.addView(selectedCountView, LayoutHelper.createFrame(42, 24, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, -8, 9));
        FrameLayout writeButtonBackground = new FrameLayout(context);
        Drawable writeButtonDrawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), getThemedColor(Theme.key_dialogFloatingButton), getThemedColor(Build.VERSION.SDK_INT >= 21 ? Theme.key_dialogFloatingButtonPressed : Theme.key_dialogFloatingButton));
        if (Build.VERSION.SDK_INT < 21) {
            Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile).mutate();
            shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
            CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
            combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            writeButtonDrawable = combinedDrawable;
        }
        writeButtonBackground.setBackgroundDrawable(writeButtonDrawable);
        writeButtonBackground.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            writeButtonBackground.setOutlineProvider(new ViewOutlineProvider() {

                @SuppressLint("NewApi")
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
                }
            });
        }
        writeButtonBackground.setOnClickListener(v -> {
            if (delegate == null || selectedDialogs.isEmpty()) {
                return;
            }
            delegate.didSelectDialogs(DialogsActivity.this, selectedDialogs, commentView.getFieldText(), false);
        });
        writeButtonBackground.setOnLongClickListener(v -> {
            if (isNextButton) {
                return false;
            }
            onSendLongClick(writeButtonBackground);
            return true;
        });
        writeButton = new ImageView[2];
        for (int a = 0; a < 2; ++a) {
            writeButton[a] = new ImageView(context);
            writeButton[a].setImageResource(a == 1 ? R.drawable.actionbtn_next : R.drawable.attach_send);
            writeButton[a].setColorFilter(new PorterDuffColorFilter(getThemedColor(Theme.key_dialogFloatingIcon), PorterDuff.Mode.MULTIPLY));
            writeButton[a].setScaleType(ImageView.ScaleType.CENTER);
            writeButtonBackground.addView(writeButton[a], LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, Gravity.CENTER));
        }
        AndroidUtilities.updateViewVisibilityAnimated(writeButton[0], true, 0.5f, false);
        AndroidUtilities.updateViewVisibilityAnimated(writeButton[1], false, 0.5f, false);
        writeButtonContainer.addView(writeButtonBackground, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, Gravity.LEFT | Gravity.TOP, Build.VERSION.SDK_INT >= 21 ? 2 : 0, 0, 0, 0));
    }
    if (filterTabsView != null) {
        contentView.addView(filterTabsView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 44));
    }
    if (!onlySelect) {
        final FrameLayout.LayoutParams layoutParams = LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT);
        if (inPreviewMode && Build.VERSION.SDK_INT >= 21) {
            layoutParams.topMargin = AndroidUtilities.statusBarHeight;
        }
        contentView.addView(actionBar, layoutParams);
    }
    if (searchString == null && initialDialogsType == 0) {
        updateLayout = new FrameLayout(context) {

            private Paint paint = new Paint();

            private Matrix matrix = new Matrix();

            private LinearGradient updateGradient;

            private int lastGradientWidth;

            @Override
            public void draw(Canvas canvas) {
                if (updateGradient != null) {
                    paint.setColor(0xffffffff);
                    paint.setShader(updateGradient);
                    updateGradient.setLocalMatrix(matrix);
                    canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint);
                    updateLayoutIcon.setBackgroundGradientDrawable(updateGradient);
                    updateLayoutIcon.draw(canvas);
                }
                super.draw(canvas);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
                int width = MeasureSpec.getSize(widthMeasureSpec);
                if (lastGradientWidth != width) {
                    updateGradient = new LinearGradient(0, 0, width, 0, new int[] { 0xff69BF72, 0xff53B3AD }, new float[] { 0.0f, 1.0f }, Shader.TileMode.CLAMP);
                    lastGradientWidth = width;
                }
                int x = (getMeasuredWidth() - updateTextView.getMeasuredWidth()) / 2;
                updateLayoutIcon.setProgressRect(x, AndroidUtilities.dp(13), x + AndroidUtilities.dp(22), AndroidUtilities.dp(13 + 22));
            }

            @Override
            public void setTranslationY(float translationY) {
                super.setTranslationY(translationY);
                additionalFloatingTranslation2 = AndroidUtilities.dp(48) - translationY;
                if (additionalFloatingTranslation2 < 0) {
                    additionalFloatingTranslation2 = 0;
                }
                if (!floatingHidden) {
                    updateFloatingButtonOffset();
                }
            }
        };
        updateLayout.setWillNotDraw(false);
        updateLayout.setVisibility(View.INVISIBLE);
        updateLayout.setTranslationY(AndroidUtilities.dp(48));
        if (Build.VERSION.SDK_INT >= 21) {
            updateLayout.setBackground(Theme.getSelectorDrawable(0x40ffffff, false));
        }
        contentView.addView(updateLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.BOTTOM));
        updateLayout.setOnClickListener(v -> {
            if (!SharedConfig.isAppUpdateAvailable()) {
                return;
            }
            AndroidUtilities.openForView(SharedConfig.pendingAppUpdate.document, true, getParentActivity());
        });
        updateLayoutIcon = new RadialProgress2(updateLayout);
        updateLayoutIcon.setColors(0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff);
        updateLayoutIcon.setCircleRadius(AndroidUtilities.dp(11));
        updateLayoutIcon.setAsMini();
        updateLayoutIcon.setIcon(MediaActionDrawable.ICON_UPDATE, true, false);
        updateTextView = new TextView(context);
        updateTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
        updateTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        updateTextView.setText(LocaleController.getString("AppUpdateNow", R.string.AppUpdateNow).toUpperCase());
        updateTextView.setTextColor(0xffffffff);
        updateTextView.setPadding(AndroidUtilities.dp(30), 0, 0, 0);
        updateLayout.addView(updateTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 0, 0, 0));
    }
    for (int a = 0; a < 2; a++) {
        undoView[a] = new UndoView(context) {

            @Override
            public void setTranslationY(float translationY) {
                super.setTranslationY(translationY);
                if (this == undoView[0] && undoView[1].getVisibility() != VISIBLE) {
                    additionalFloatingTranslation = getMeasuredHeight() + AndroidUtilities.dp(8) - translationY;
                    if (additionalFloatingTranslation < 0) {
                        additionalFloatingTranslation = 0;
                    }
                    if (!floatingHidden) {
                        updateFloatingButtonOffset();
                    }
                }
            }

            @Override
            protected boolean canUndo() {
                for (int a = 0; a < viewPages.length; a++) {
                    if (viewPages[a].dialogsItemAnimator.isRunning()) {
                        return false;
                    }
                }
                return true;
            }

            @Override
            protected void onRemoveDialogAction(long currentDialogId, int action) {
                if (action == UndoView.ACTION_DELETE || action == UndoView.ACTION_DELETE_FEW) {
                    debugLastUpdateAction = 1;
                    setDialogsListFrozen(true);
                    if (frozenDialogsList != null) {
                        int selectedIndex = -1;
                        for (int i = 0; i < frozenDialogsList.size(); i++) {
                            if (frozenDialogsList.get(i).id == currentDialogId) {
                                selectedIndex = i;
                                break;
                            }
                        }
                        if (selectedIndex >= 0) {
                            TLRPC.Dialog dialog = frozenDialogsList.remove(selectedIndex);
                            viewPages[0].dialogsAdapter.notifyDataSetChanged();
                            int finalSelectedIndex = selectedIndex;
                            AndroidUtilities.runOnUIThread(() -> {
                                if (frozenDialogsList != null) {
                                    frozenDialogsList.add(finalSelectedIndex, dialog);
                                    viewPages[0].dialogsAdapter.notifyItemInserted(finalSelectedIndex);
                                    dialogInsertFinished = 2;
                                }
                            });
                        } else {
                            setDialogsListFrozen(false);
                        }
                    }
                }
            }
        };
        contentView.addView(undoView[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    }
    if (folderId != 0) {
        viewPages[0].listView.setGlowColor(Theme.getColor(Theme.key_actionBarDefaultArchived));
        actionBar.setTitleColor(Theme.getColor(Theme.key_actionBarDefaultArchivedTitle));
        actionBar.setItemsColor(Theme.getColor(Theme.key_actionBarDefaultArchivedIcon), false);
        actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_actionBarDefaultArchivedSelector), false);
        actionBar.setSearchTextColor(Theme.getColor(Theme.key_actionBarDefaultArchivedSearch), false);
        actionBar.setSearchTextColor(Theme.getColor(Theme.key_actionBarDefaultArchivedSearchPlaceholder), true);
    }
    if (!onlySelect && initialDialogsType == 0) {
        blurredView = new View(context) {

            @Override
            public void setAlpha(float alpha) {
                super.setAlpha(alpha);
                if (fragmentView != null) {
                    fragmentView.invalidate();
                }
            }
        };
        blurredView.setVisibility(View.GONE);
        contentView.addView(blurredView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    }
    actionBarDefaultPaint.setColor(Theme.getColor(folderId == 0 ? Theme.key_actionBarDefault : Theme.key_actionBarDefaultArchived));
    if (inPreviewMode) {
        final TLRPC.User currentUser = getUserConfig().getCurrentUser();
        avatarContainer = new ChatAvatarContainer(actionBar.getContext(), null, false);
        avatarContainer.setTitle(UserObject.getUserName(currentUser));
        avatarContainer.setSubtitle(LocaleController.formatUserStatus(currentAccount, currentUser));
        avatarContainer.setUserAvatar(currentUser, true);
        avatarContainer.setOccupyStatusBar(false);
        avatarContainer.setLeftPadding(AndroidUtilities.dp(10));
        actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 40, 0));
        floatingButton.setVisibility(View.INVISIBLE);
        actionBar.setOccupyStatusBar(false);
        actionBar.setBackgroundColor(Theme.getColor(Theme.key_actionBarDefault));
        if (fragmentContextView != null) {
            contentView.removeView(fragmentContextView);
        }
        if (fragmentLocationContextView != null) {
            contentView.removeView(fragmentLocationContextView);
        }
    }
    searchIsShowed = false;
    updateFilterTabs(false, false);
    if (searchString != null) {
        showSearch(true, false);
        actionBar.openSearchField(searchString, false);
    } else if (initialSearchString != null) {
        showSearch(true, false);
        actionBar.openSearchField(initialSearchString, false);
        initialSearchString = null;
        if (filterTabsView != null) {
            filterTabsView.setTranslationY(-AndroidUtilities.dp(44));
        }
    } else {
        showSearch(false, false);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        FilesMigrationService.checkBottomSheet(this);
    }
    updateMenuButton(false);
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) StickersAlert(org.telegram.ui.Components.StickersAlert) RecyclerAnimationScrollHelper(org.telegram.ui.Components.RecyclerAnimationScrollHelper) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) Bulletin(org.telegram.ui.Components.Bulletin) Property(android.util.Property) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) MediaActionDrawable(org.telegram.ui.Components.MediaActionDrawable) FilterTabsView(org.telegram.ui.Components.FilterTabsView) Manifest(android.Manifest) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) StateListAnimator(android.animation.StateListAnimator) DrawerProfileCell(org.telegram.ui.Cells.DrawerProfileCell) PullForegroundDrawable(org.telegram.ui.Components.PullForegroundDrawable) Shader(android.graphics.Shader) Canvas(android.graphics.Canvas) TargetApi(android.annotation.TargetApi) NotificationsController(org.telegram.messenger.NotificationsController) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) Interpolator(android.view.animation.Interpolator) UndoView(org.telegram.ui.Components.UndoView) AnimationProperties(org.telegram.ui.Components.AnimationProperties) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationCenter(org.telegram.messenger.NotificationCenter) MenuDrawable(org.telegram.ui.ActionBar.MenuDrawable) RecyclerItemsEnterAnimator(org.telegram.ui.Components.RecyclerItemsEnterAnimator) Outline(android.graphics.Outline) HapticFeedbackConstants(android.view.HapticFeedbackConstants) DialogsAdapter(org.telegram.ui.Adapters.DialogsAdapter) TextPaint(android.text.TextPaint) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DividerCell(org.telegram.ui.Cells.DividerCell) FileLoader(org.telegram.messenger.FileLoader) ViewParent(android.view.ViewParent) ViewPager(androidx.viewpager.widget.ViewPager) Dialog(android.app.Dialog) DialogsSearchAdapter(org.telegram.ui.Adapters.DialogsSearchAdapter) SwipeGestureSettingsView(org.telegram.ui.Components.SwipeGestureSettingsView) AlertsCreator(org.telegram.ui.Components.AlertsCreator) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) ArrayList(java.util.ArrayList) ItemTouchHelper(androidx.recyclerview.widget.ItemTouchHelper) FragmentContextView(org.telegram.ui.Components.FragmentContextView) TLRPC(org.telegram.tgnet.TLRPC) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) DialogsEmptyCell(org.telegram.ui.Cells.DialogsEmptyCell) FilesMigrationService(org.telegram.messenger.FilesMigrationService) DialogCell(org.telegram.ui.Cells.DialogCell) ProfileSearchCell(org.telegram.ui.Cells.ProfileSearchCell) JoinGroupAlert(org.telegram.ui.Components.JoinGroupAlert) SearchViewPager(org.telegram.ui.Components.SearchViewPager) ViewPagerFixed(org.telegram.ui.Components.ViewPagerFixed) LinearGradient(android.graphics.LinearGradient) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) UserCell(org.telegram.ui.Cells.UserCell) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) TextUtils(android.text.TextUtils) DialogsItemAnimator(org.telegram.ui.Components.DialogsItemAnimator) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) DrawerAddCell(org.telegram.ui.Cells.DrawerAddCell) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ScrollView(android.widget.ScrollView) ContactsController(org.telegram.messenger.ContactsController) GraySectionCell(org.telegram.ui.Cells.GraySectionCell) Configuration(android.content.res.Configuration) ColorUtils(androidx.core.graphics.ColorUtils) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) EditText(android.widget.EditText) ValueAnimator(android.animation.ValueAnimator) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) FiltersView(org.telegram.ui.Adapters.FiltersView) Rect(android.graphics.Rect) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) RadialProgress2(org.telegram.ui.Components.RadialProgress2) PackageManager(android.content.pm.PackageManager) WindowManager(android.view.WindowManager) AccountInstance(org.telegram.messenger.AccountInstance) AndroidUtilities(org.telegram.messenger.AndroidUtilities) CubicBezierInterpolator(org.telegram.ui.Components.CubicBezierInterpolator) Animator(android.animation.Animator) AccelerateDecelerateInterpolator(android.view.animation.AccelerateDecelerateInterpolator) ViewConfiguration(android.view.ViewConfiguration) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) ApplicationLoader(org.telegram.messenger.ApplicationLoader) PacmanAnimation(org.telegram.ui.Components.PacmanAnimation) TextCell(org.telegram.ui.Cells.TextCell) ArchiveHintInnerCell(org.telegram.ui.Cells.ArchiveHintInnerCell) View(android.view.View) Button(android.widget.Button) RecyclerView(androidx.recyclerview.widget.RecyclerView) Matrix(android.graphics.Matrix) RectF(android.graphics.RectF) ImageLoader(org.telegram.messenger.ImageLoader) DrawerUserCell(org.telegram.ui.Cells.DrawerUserCell) Utilities(org.telegram.messenger.Utilities) RLottieImageView(org.telegram.ui.Components.RLottieImageView) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) BitmapDrawable(android.graphics.drawable.BitmapDrawable) PorterDuff(android.graphics.PorterDuff) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ViewGroup(android.view.ViewGroup) StateSet(android.util.StateSet) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Context(android.content.Context) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) KeyEvent(android.view.KeyEvent) Theme(org.telegram.ui.ActionBar.Theme) ViewOutlineProvider(android.view.ViewOutlineProvider) BulletinFactory(org.telegram.ui.Components.BulletinFactory) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) VelocityTracker(android.view.VelocityTracker) XiaomiUtilities(org.telegram.messenger.XiaomiUtilities) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) FiltersListBottomSheet(org.telegram.ui.Components.FiltersListBottomSheet) ActionBar(org.telegram.ui.ActionBar.ActionBar) LinearSmoothScrollerCustom(androidx.recyclerview.widget.LinearSmoothScrollerCustom) TLObject(org.telegram.tgnet.TLObject) HintDialogCell(org.telegram.ui.Cells.HintDialogCell) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) BuildVars(org.telegram.messenger.BuildVars) MediaDataController(org.telegram.messenger.MediaDataController) Build(android.os.Build) DrawerActionCell(org.telegram.ui.Cells.DrawerActionCell) DialogInterface(android.content.DialogInterface) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) DialogObject(org.telegram.messenger.DialogObject) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) AccountSelectCell(org.telegram.ui.Cells.AccountSelectCell) FlickerLoadingView(org.telegram.ui.Components.FlickerLoadingView) MessagesController(org.telegram.messenger.MessagesController) Color(android.graphics.Color) NumberTextView(org.telegram.ui.Components.NumberTextView) HashtagSearchCell(org.telegram.ui.Cells.HashtagSearchCell) Bitmap(android.graphics.Bitmap) ViewTreeObserver(android.view.ViewTreeObserver) Vibrator(android.os.Vibrator) ProxyDrawable(org.telegram.ui.Components.ProxyDrawable) Activity(android.app.Activity) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LoadingCell(org.telegram.ui.Cells.LoadingCell) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) ArrayList(java.util.ArrayList) ActionBarPopupWindow(org.telegram.ui.ActionBar.ActionBarPopupWindow) Matrix(android.graphics.Matrix) Button(android.widget.Button) AccountSelectCell(org.telegram.ui.Cells.AccountSelectCell) EditText(android.widget.EditText) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Rect(android.graphics.Rect) ChatAvatarContainer(org.telegram.ui.Components.ChatAvatarContainer) MenuDrawable(org.telegram.ui.ActionBar.MenuDrawable) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) MediaActionDrawable(org.telegram.ui.Components.MediaActionDrawable) PullForegroundDrawable(org.telegram.ui.Components.PullForegroundDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) MenuDrawable(org.telegram.ui.ActionBar.MenuDrawable) BitmapDrawable(android.graphics.drawable.BitmapDrawable) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) ProxyDrawable(org.telegram.ui.Components.ProxyDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) LinearGradient(android.graphics.LinearGradient) DialogsSearchAdapter(org.telegram.ui.Adapters.DialogsSearchAdapter) MessagesController(org.telegram.messenger.MessagesController) SearchViewPager(org.telegram.ui.Components.SearchViewPager) FiltersView(org.telegram.ui.Adapters.FiltersView) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ItemTouchHelper(androidx.recyclerview.widget.ItemTouchHelper) UndoView(org.telegram.ui.Components.UndoView) DialogsAdapter(org.telegram.ui.Adapters.DialogsAdapter) FlickerLoadingView(org.telegram.ui.Components.FlickerLoadingView) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) RecyclerAnimationScrollHelper(org.telegram.ui.Components.RecyclerAnimationScrollHelper) Outline(android.graphics.Outline) ViewOutlineProvider(android.view.ViewOutlineProvider) StateListAnimator(android.animation.StateListAnimator) RecyclerItemsEnterAnimator(org.telegram.ui.Components.RecyclerItemsEnterAnimator) DialogsItemAnimator(org.telegram.ui.Components.DialogsItemAnimator) ValueAnimator(android.animation.ValueAnimator) Animator(android.animation.Animator) ObjectAnimator(android.animation.ObjectAnimator) SuppressLint(android.annotation.SuppressLint) RecyclerView(androidx.recyclerview.widget.RecyclerView) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TLRPC(org.telegram.tgnet.TLRPC) RadialProgress2(org.telegram.ui.Components.RadialProgress2) BackupImageView(org.telegram.ui.Components.BackupImageView) Dialog(android.app.Dialog) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) TextView(android.widget.TextView) NumberTextView(org.telegram.ui.Components.NumberTextView) ImageView(android.widget.ImageView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) BackupImageView(org.telegram.ui.Components.BackupImageView) ProxyDrawable(org.telegram.ui.Components.ProxyDrawable) Canvas(android.graphics.Canvas) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) PullForegroundDrawable(org.telegram.ui.Components.PullForegroundDrawable) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) RecyclerItemsEnterAnimator(org.telegram.ui.Components.RecyclerItemsEnterAnimator) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) FilterTabsView(org.telegram.ui.Components.FilterTabsView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) StateListAnimator(android.animation.StateListAnimator) BackDrawable(org.telegram.ui.ActionBar.BackDrawable) AnimatorSet(android.animation.AnimatorSet) DialogsItemAnimator(org.telegram.ui.Components.DialogsItemAnimator) DialogCell(org.telegram.ui.Cells.DialogCell) HintDialogCell(org.telegram.ui.Cells.HintDialogCell) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) ActionBarMenuSubItem(org.telegram.ui.ActionBar.ActionBarMenuSubItem) Bundle(android.os.Bundle) ImageView(android.widget.ImageView) FilterTabsView(org.telegram.ui.Components.FilterTabsView) UndoView(org.telegram.ui.Components.UndoView) SwipeGestureSettingsView(org.telegram.ui.Components.SwipeGestureSettingsView) FragmentContextView(org.telegram.ui.Components.FragmentContextView) ScrollView(android.widget.ScrollView) FiltersView(org.telegram.ui.Adapters.FiltersView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) TextView(android.widget.TextView) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) BackupImageView(org.telegram.ui.Components.BackupImageView) FlickerLoadingView(org.telegram.ui.Components.FlickerLoadingView) NumberTextView(org.telegram.ui.Components.NumberTextView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) MotionEvent(android.view.MotionEvent) LinearSmoothScrollerCustom(androidx.recyclerview.widget.LinearSmoothScrollerCustom) ChatActivityEnterView(org.telegram.ui.Components.ChatActivityEnterView) ScrollView(android.widget.ScrollView) FrameLayout(android.widget.FrameLayout) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) FragmentContextView(org.telegram.ui.Components.FragmentContextView) LinearLayout(android.widget.LinearLayout)

Example 15 with StateListAnimator

use of android.animation.StateListAnimator in project GreenHouse by utsanjan.

the class ViewUtilsLollipop method setDefaultAppBarLayoutStateListAnimator.

/* JADX INFO: Access modifiers changed from: package-private */
public static void setDefaultAppBarLayoutStateListAnimator(View view, float elevation) {
    int dur = view.getResources().getInteger(R.integer.app_bar_elevation_anim_duration);
    StateListAnimator sla = new StateListAnimator();
    sla.addState(new int[] { 16842766, R.attr.state_liftable, -R.attr.state_lifted }, ObjectAnimator.ofFloat(view, "elevation", 0.0f).setDuration(dur));
    sla.addState(new int[] { 16842766 }, ObjectAnimator.ofFloat(view, "elevation", elevation).setDuration(dur));
    sla.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0.0f).setDuration(0L));
    view.setStateListAnimator(sla);
}
Also used : StateListAnimator(android.animation.StateListAnimator)

Aggregations

StateListAnimator (android.animation.StateListAnimator)25 SuppressLint (android.annotation.SuppressLint)11 Drawable (android.graphics.drawable.Drawable)10 View (android.view.View)10 ImageView (android.widget.ImageView)10 Outline (android.graphics.Outline)9 PorterDuffColorFilter (android.graphics.PorterDuffColorFilter)9 ViewOutlineProvider (android.view.ViewOutlineProvider)9 ActionBar (org.telegram.ui.ActionBar.ActionBar)9 CombinedDrawable (org.telegram.ui.Components.CombinedDrawable)9 AnimatorSet (android.animation.AnimatorSet)8 Context (android.content.Context)8 LinearLayoutManager (androidx.recyclerview.widget.LinearLayoutManager)8 RecyclerView (androidx.recyclerview.widget.RecyclerView)8 RecyclerListView (org.telegram.ui.Components.RecyclerListView)8 Paint (android.graphics.Paint)7 ViewGroup (android.view.ViewGroup)7 FrameLayout (android.widget.FrameLayout)7 Animator (android.animation.Animator)6 ObjectAnimator (android.animation.ObjectAnimator)6