Example usage for android.view View setBackgroundColor

List of usage examples for android.view View setBackgroundColor

Introduction

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

Prototype

@RemotableViewMethod
public void setBackgroundColor(@ColorInt int color) 

Source Link

Document

Sets the background color for this view.

Usage

From source file:im.vector.adapters.VectorRoomSummaryAdapter.java

/**
 * Compute the View that should be used to render the child,
 * given its position and its groups position
 *//*from   w w w.j a  v a2  s . co m*/
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
        ViewGroup parent) {
    // sanity check
    if (null == mSummaryListByGroupPosition) {
        return null;
    }
    if (convertView == null) {
        convertView = mLayoutInflater.inflate(mChildLayoutResourceId, parent, false);
    }

    if (!mMxSession.isAlive()) {
        return convertView;
    }

    int roomNameBlack = ThemeUtils.getColor(mContext, R.attr.riot_primary_text_color);
    int fushiaColor = ContextCompat.getColor(mContext, R.color.vector_fuchsia_color);
    int vectorDefaultTimeStampColor = ThemeUtils.getColor(mContext, R.attr.default_text_light_color);
    int vectorGreenColor = ContextCompat.getColor(mContext, R.color.vector_green_color);
    int vectorSilverColor = ContextCompat.getColor(mContext, R.color.vector_silver_color);

    // retrieve the UI items
    ImageView avatarImageView = convertView.findViewById(R.id.room_avatar);
    TextView roomNameTxtView = convertView.findViewById(R.id.roomSummaryAdapter_roomName);
    TextView roomMsgTxtView = convertView.findViewById(R.id.roomSummaryAdapter_roomMessage);
    View bingUnreadMsgView = convertView.findViewById(R.id.bing_indicator_unread_message);
    TextView timestampTxtView = convertView.findViewById(R.id.roomSummaryAdapter_ts);
    View separatorView = convertView.findViewById(R.id.recents_separator);
    View separatorGroupView = convertView.findViewById(R.id.recents_groups_separator_line);
    final View actionView = convertView.findViewById(R.id.roomSummaryAdapter_action);
    final ImageView actionImageView = convertView.findViewById(R.id.roomSummaryAdapter_action_image);
    TextView unreadCountTxtView = convertView.findViewById(R.id.roomSummaryAdapter_unread_count);
    View directChatIcon = convertView.findViewById(R.id.room_avatar_direct_chat_icon);
    View encryptedIcon = convertView.findViewById(R.id.room_avatar_encrypted_icon);

    View invitationView = convertView.findViewById(R.id.recents_groups_invitation_group);
    Button preViewButton = convertView.findViewById(R.id.recents_invite_preview_button);
    Button rejectButton = convertView.findViewById(R.id.recents_invite_reject_button);

    View showMoreView = convertView.findViewById(R.id.roomSummaryAdapter_show_more_layout);
    View actionClickArea = convertView.findViewById(R.id.roomSummaryAdapter_action_click_area);

    // directory management
    if ((mDirectoryGroupPosition == groupPosition) || (mRoomByAliasGroupPosition == groupPosition)) {
        // some items are show
        bingUnreadMsgView.setVisibility(View.INVISIBLE);
        timestampTxtView.setVisibility(View.GONE);
        actionImageView.setVisibility(View.GONE);
        invitationView.setVisibility(View.GONE);
        separatorView.setVisibility(View.GONE);
        separatorGroupView.setVisibility(View.VISIBLE);
        showMoreView.setVisibility(View.VISIBLE);
        actionClickArea.setVisibility(View.GONE);
        unreadCountTxtView.setVisibility(View.GONE);
        directChatIcon.setVisibility(View.GONE);
        encryptedIcon.setVisibility(View.GONE);

        if (mDirectoryGroupPosition == groupPosition) {
            roomNameTxtView.setText(mContext.getResources().getString(R.string.directory_search_results_title));

            if (!TextUtils.isEmpty(mSearchedPattern)) {
                if (null == mMatchedPublicRoomsCount) {
                    roomMsgTxtView
                            .setText(mContext.getResources().getString(R.string.directory_searching_title));
                } else {
                    String value = mMatchedPublicRoomsCount.toString();

                    if (mMatchedPublicRoomsCount >= PublicRoomsManager.PUBLIC_ROOMS_LIMIT) {
                        value = "> " + PublicRoomsManager.PUBLIC_ROOMS_LIMIT;
                    }

                    roomMsgTxtView.setText(
                            mContext.getResources().getQuantityString(R.plurals.directory_search_rooms_for,
                                    mMatchedPublicRoomsCount, value, mSearchedPattern));
                }
            } else {
                if (null == mPublicRoomsCount) {
                    roomMsgTxtView.setText(null);
                } else {
                    roomMsgTxtView.setText(mContext.getResources().getQuantityString(
                            R.plurals.directory_search_rooms, mPublicRoomsCount, mPublicRoomsCount));
                }
            }

            avatarImageView.setImageBitmap(VectorUtils.getAvatar(avatarImageView.getContext(),
                    VectorUtils.getAvatarColor(null), null, true));
        } else {
            roomNameTxtView.setText(mSearchedPattern);
            roomMsgTxtView.setText("");
            avatarImageView.setImageBitmap(VectorUtils.getAvatar(avatarImageView.getContext(),
                    VectorUtils.getAvatarColor(null), "@", true));
        }
        return convertView;
    }

    showMoreView.setVisibility(View.GONE);

    RoomSummary childRoomSummary = mSummaryListByGroupPosition.get(groupPosition).get(childPosition);
    final Room childRoom = mMxSession.getDataHandler().getStore().getRoom(childRoomSummary.getRoomId());
    int unreadMsgCount = childRoomSummary.getUnreadEventsCount();
    int highlightCount = 0;
    int notificationCount = 0;

    if (null != childRoom) {
        highlightCount = childRoom.getHighlightCount();
        notificationCount = childRoom.getNotificationCount();

        if (mMxSession.getDataHandler().getBingRulesManager().isRoomMentionOnly(childRoom.getRoomId())) {
            notificationCount = highlightCount;
        }
    }

    // get last message to be displayed
    CharSequence lastMsgToDisplay = getChildMessageToDisplay(childRoomSummary);

    // display the room avatar
    final String roomName = VectorUtils.getRoomDisplayName(mContext, mMxSession, childRoom);
    VectorUtils.loadRoomAvatar(mContext, mMxSession, avatarImageView, childRoom);

    // display the room name
    roomNameTxtView.setText(roomName);
    roomNameTxtView.setTextColor(roomNameBlack);
    roomNameTxtView.setTypeface(null, (0 != unreadMsgCount) ? Typeface.BOLD : Typeface.NORMAL);

    // display the last message
    roomMsgTxtView.setText(lastMsgToDisplay);

    // set the timestamp
    timestampTxtView.setText(getFormattedTimestamp(childRoomSummary.getLatestReceivedEvent()));
    timestampTxtView.setTextColor(vectorDefaultTimeStampColor);
    timestampTxtView.setTypeface(null, Typeface.NORMAL);

    // set bing view background colour
    int bingUnreadColor;
    if (0 != highlightCount) {
        bingUnreadColor = fushiaColor;
    } else if (0 != notificationCount) {
        bingUnreadColor = vectorGreenColor;
    } else if (0 != unreadMsgCount) {
        bingUnreadColor = vectorSilverColor;
    } else {
        bingUnreadColor = Color.TRANSPARENT;
    }
    bingUnreadMsgView.setBackgroundColor(bingUnreadColor);

    // display the unread badge counter
    if ((0 != notificationCount)) {
        unreadCountTxtView.setVisibility(View.VISIBLE);
        unreadCountTxtView.setText(String.valueOf(notificationCount));
        unreadCountTxtView.setTypeface(null, Typeface.BOLD);
        setUnreadBackground(unreadCountTxtView, bingUnreadColor);
    } else {
        unreadCountTxtView.setVisibility(View.GONE);
    }

    // some items are shown
    boolean isInvited = false;

    if (null != childRoom) {
        isInvited = childRoom.isInvited();
    }

    if (null != childRoom) {
        directChatIcon.setVisibility(
                RoomUtils.isDirectChat(mMxSession, childRoom.getRoomId()) ? View.VISIBLE : View.GONE);
        encryptedIcon.setVisibility(childRoom.isEncrypted() ? View.VISIBLE : View.GONE);
    } else {
        directChatIcon.setVisibility(View.GONE);
        encryptedIcon.setVisibility(View.GONE);
    }

    bingUnreadMsgView.setVisibility(isInvited ? View.INVISIBLE : View.VISIBLE);
    invitationView.setVisibility(isInvited ? View.VISIBLE : View.GONE);

    final String fRoomId = childRoomSummary.getRoomId();

    if (isInvited) {
        actionClickArea.setVisibility(View.GONE);

        preViewButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    mListener.onPreviewRoom(mMxSession, fRoomId);
                }
            }
        });

        rejectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    mListener.onRejectInvitation(mMxSession, fRoomId);
                }
            }
        });

        // display an exclamation mark like the webclient
        unreadCountTxtView.setVisibility(View.VISIBLE);
        unreadCountTxtView.setText("!");
        unreadCountTxtView.setTypeface(null, Typeface.BOLD);
        setUnreadBackground(unreadCountTxtView, fushiaColor);
        timestampTxtView.setVisibility(View.GONE);
        actionImageView.setVisibility(View.GONE);
    } else {

        final boolean isFavorite = groupPosition == mFavouritesGroupPosition;
        final boolean isLowPrior = groupPosition == mLowPriorGroupPosition;

        actionClickArea.setVisibility(View.VISIBLE);
        actionClickArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RoomUtils.displayPopupMenu(mContext, mMxSession, childRoom, actionView, isFavorite, isLowPrior,
                        mMoreActionListener);
            }
        });

        timestampTxtView.setVisibility(mIsSearchMode ? View.INVISIBLE : View.VISIBLE);
        actionImageView.setVisibility(mIsSearchMode ? View.INVISIBLE : View.VISIBLE);
    }

    separatorView.setVisibility(isLastChild ? View.GONE : View.VISIBLE);
    separatorGroupView
            .setVisibility((isLastChild && ((groupPosition + 1) < getGroupCount())) ? View.VISIBLE : View.GONE);

    return convertView;
}

From source file:com.philliphsu.bottomsheetpickers.time.grid.GridTimePickerDialog.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = super.onCreateView(inflater, container, savedInstanceState);
    KeyboardListener keyboardListener = new KeyboardListener();
    view.findViewById(R.id.time_picker_dialog).setOnKeyListener(keyboardListener);

    if (!mThemeSetAtRuntime) {
        mThemeDark = Utils.isDarkTheme(getActivity(), mThemeDark);
    }//from  ww  w.  j  av a  2s  .co  m

    final Resources res = getResources();
    final Context ctx = getActivity();
    mHourPickerDescription = res.getString(R.string.hour_picker_description);
    mSelectHours = res.getString(R.string.select_hours);
    mMinutePickerDescription = res.getString(R.string.minute_picker_description);
    mSelectMinutes = res.getString(R.string.select_minutes);
    mSelectedColor = getColor(ctx, android.R.color.white);
    mUnselectedColor = getColor(ctx, R.color.unselected_color);

    mHourView = (TextView) view.findViewById(R.id.hours);
    mHourView.setOnKeyListener(keyboardListener);
    mHourSpaceView = (TextView) view.findViewById(R.id.hour_space);
    mMinuteSpaceView = (TextView) view.findViewById(R.id.minutes_space);
    mMinuteView = (TextView) view.findViewById(R.id.minutes);
    mMinuteView.setOnKeyListener(keyboardListener);
    mAmPmTextView = (TextView) view.findViewById(R.id.ampm_label);
    mAmPmTextView.setOnKeyListener(keyboardListener);
    String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
    mAmText = amPmTexts[0];
    mPmText = amPmTexts[1];

    // TODO: Restore
    //        mHapticFeedbackController = new HapticFeedbackController(getActivity());
    mTimePicker = (GridPickerLayout) view.findViewById(R.id.time_picker);
    mTimePicker.setOnValueSelectedListener(this);
    mTimePicker.setOnKeyListener(keyboardListener);
    mTimePicker.initialize(getActivity(), /*mHapticFeedbackController,*/ mInitialHourOfDay, mInitialMinute,
            mIs24HourMode);

    int currentItemShowing = HOUR_INDEX;
    if (savedInstanceState != null && savedInstanceState.containsKey(KEY_CURRENT_ITEM_SHOWING)) {
        currentItemShowing = savedInstanceState.getInt(KEY_CURRENT_ITEM_SHOWING);
    }
    setCurrentItemShowing(currentItemShowing, false, true, true);
    mTimePicker.invalidate();

    mHourView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setCurrentItemShowing(HOUR_INDEX, true, false, true);
            tryVibrate();
        }
    });
    mMinuteView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            setCurrentItemShowing(MINUTE_INDEX, true, false, true);
            tryVibrate();
        }
    });

    mDoneButton = (FloatingActionButton) view.findViewById(R.id.fab);
    mDoneButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mInKbMode && isTypedTimeFullyLegal()) {
                finishKbMode(false);
            } else {
                tryVibrate();
            }
            onTimeSet(mTimePicker, mTimePicker.getHours(), mTimePicker.getMinutes());
        }
    });
    mDoneButton.setOnKeyListener(keyboardListener);

    // TODO: setOnKeyListener?
    mFirstHalfDayToggle = (Button) view.findViewById(R.id.half_day_toggle_1);
    mFirstHalfDayToggle.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            tryToggleHalfDay(HALF_DAY_1);
        }
    });
    // TODO: setOnKeyListener?
    mSecondHalfDayToggle = (Button) view.findViewById(R.id.half_day_toggle_2);
    mSecondHalfDayToggle.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            tryToggleHalfDay(HALF_DAY_2);
        }
    });

    // Enable or disable the AM/PM view.
    mAmPmHitspace = view.findViewById(R.id.ampm_hitspace);
    if (mIs24HourMode) {
        mAmPmTextView.setVisibility(View.GONE);

        RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        paramsSeparator.addRule(RelativeLayout.CENTER_IN_PARENT);
        TextView separatorView = (TextView) view.findViewById(R.id.separator);
        separatorView.setLayoutParams(paramsSeparator);

        mFirstHalfDayToggle.setText(R.string.hours_00_11);
        mSecondHalfDayToggle.setText(R.string.hours_12_23);
        // We need different drawable resources for each case, not a single one that we
        // just tint differently, because the orientation of each one is different.
        final int icon1 = mThemeDark ? R.drawable.ic_half_day_1_dark_24dp : R.drawable.ic_half_day_1_24dp;
        final int icon2 = mThemeDark ? R.drawable.ic_half_day_2_dark_24dp : R.drawable.ic_half_day_2_24dp;
        mFirstHalfDayToggle.setCompoundDrawablesWithIntrinsicBounds(0, icon1, 0, 0);
        mSecondHalfDayToggle.setCompoundDrawablesWithIntrinsicBounds(0, icon2, 0, 0);
    } else {
        mAmPmTextView.setVisibility(View.VISIBLE);
        mAmPmHitspace.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                tryVibrate();
                int amOrPm = mTimePicker.getIsCurrentlyAmOrPm();
                if (amOrPm == HALF_DAY_1) {
                    amOrPm = HALF_DAY_2;
                } else if (amOrPm == HALF_DAY_2) {
                    amOrPm = HALF_DAY_1;
                }
                updateHalfDay(amOrPm);
                mTimePicker.setHalfDay(amOrPm);
            }
        });
        mFirstHalfDayToggle.setText(mAmText);
        mSecondHalfDayToggle.setText(mPmText);
    }

    mAllowAutoAdvance = true;
    setHour(mInitialHourOfDay, true);
    setMinute(mInitialMinute);

    // Set up for keyboard mode.
    mDoublePlaceholderText = res.getString(R.string.time_placeholder);
    mDeletedKeyFormat = res.getString(R.string.deleted_key);
    mPlaceholderText = mDoublePlaceholderText.charAt(0);
    mAmKeyCode = mPmKeyCode = -1;
    generateLegalTimesTree();
    if (mInKbMode) {
        mTypedTimes = savedInstanceState.getIntegerArrayList(KEY_TYPED_TIMES);
        tryStartingKbMode(-1);
        mHourView.invalidate();
    } else if (mTypedTimes == null) {
        mTypedTimes = new ArrayList<Integer>();
    }

    // Set the theme at the end so that the initialize()s above don't counteract the theme.
    //
    // If you decide to move the FAB and the half day toggles to the GridPickerLayout
    // class, you should remove getApplicationContext(). Otherwise, you would not
    // retrieve the correct accent color.
    mTimePicker.setTheme(getActivity().getApplicationContext(), mThemeDark);
    // Prepare some colors to use.
    final int white = getColor(ctx, android.R.color.white);
    final int darkGray = getColor(ctx, R.color.dark_gray);
    final int lightGray = getColor(ctx, R.color.light_gray);
    final int accentColor = Utils.getThemeAccentColor(getActivity());
    final int sidebarDark = getColor(ctx, R.color.sidebar_color_dark);
    final int sidebarLight = getColor(ctx, R.color.sidebar_color_light);

    // Set the whole view's background color first
    view.setBackgroundColor(mThemeDark ? darkGray : white);
    // Set the colors for each view based on the theme.
    view.findViewById(R.id.time_display_background).setBackgroundColor(mThemeDark ? lightGray : accentColor);
    view.findViewById(R.id.time_display).setBackgroundColor(mThemeDark ? lightGray : accentColor);
    ((TextView) view.findViewById(R.id.separator)).setTextColor(mUnselectedColor);
    ((TextView) view.findViewById(R.id.ampm_label)).setTextColor(mUnselectedColor);
    view.findViewById(R.id.sidebar).setBackgroundColor(mThemeDark ? sidebarDark : sidebarLight);

    // Color in normal state
    mDoneButton.setBackgroundTintList(ColorStateList.valueOf(accentColor));
    //TODO        mDoneButton.setRippleColor();

    mHalfDayToggleSelectedColor = accentColor;
    mHalfDayToggleUnselectedColor = getColor(ctx,
            mThemeDark ? R.color.text_color_primary_dark : R.color.text_color_primary_light);

    Utils.setColorControlHighlight(mFirstHalfDayToggle, accentColor);
    Utils.setColorControlHighlight(mSecondHalfDayToggle, accentColor);

    // Update the half day at the end when the state colors have been initialized
    updateHalfDay(mInitialHourOfDay < 12 ? HALF_DAY_1 : HALF_DAY_2);
    return view;
}

From source file:cw.kop.autobackground.sources.SourceInfoFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Bundle arguments = getArguments();/*from   w  w w . j a v  a  2 s  .  c  o m*/
    sourcePosition = (Integer) arguments.get("position");
    int colorFilterInt = AppSettings.getColorFilterInt(appContext);

    View view = inflater.inflate(R.layout.source_info_fragment, container, false);
    headerView = inflater.inflate(R.layout.source_info_header, null, false);

    settingsContainer = (RelativeLayout) headerView.findViewById(R.id.source_settings_container);

    sourceImage = (ImageView) headerView.findViewById(R.id.source_image);
    sourceTitle = (EditText) headerView.findViewById(R.id.source_title);
    sourcePrefix = (EditText) headerView.findViewById(R.id.source_data_prefix);
    sourceData = (EditText) headerView.findViewById(R.id.source_data);
    sourceSuffix = (EditText) headerView.findViewById(R.id.source_data_suffix);
    sourceNum = (EditText) headerView.findViewById(R.id.source_num);

    ViewGroup.LayoutParams params = sourceImage.getLayoutParams();
    params.height = (int) ((container.getWidth()
            - 2f * getResources().getDimensionPixelSize(R.dimen.side_margin)) / 16f * 9);
    sourceImage.setLayoutParams(params);

    cancelButton = (Button) view.findViewById(R.id.cancel_button);
    saveButton = (Button) view.findViewById(R.id.save_button);

    sourcePrefix.setTextColor(colorFilterInt);
    sourceSuffix.setTextColor(colorFilterInt);
    cancelButton.setTextColor(colorFilterInt);
    saveButton.setTextColor(colorFilterInt);

    // Adjust alpha to get faded hint color from regular text color
    int hintColor = Color.argb(0x88, Color.red(colorFilterInt), Color.green(colorFilterInt),
            Color.blue(colorFilterInt));

    sourceTitle.setHintTextColor(hintColor);
    sourceData.setHintTextColor(hintColor);
    sourceNum.setHintTextColor(hintColor);

    sourceData.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (type) {

            case AppSettings.FOLDER:
                selectSource(getPositionOfType(AppSettings.FOLDER));
                break;
            case AppSettings.GOOGLE_ALBUM:
                selectSource(getPositionOfType(AppSettings.GOOGLE_ALBUM));
                break;

            }
            Log.i(TAG, "Data launched folder fragment");
        }
    });

    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            saveSource();
        }
    });

    sourceSpinnerText = (TextView) headerView.findViewById(R.id.source_spinner_text);
    sourceSpinner = (Spinner) headerView.findViewById(R.id.source_spinner);

    timePref = (CustomSwitchPreference) findPreference("source_time");
    timePref.setChecked(arguments.getBoolean("use_time"));
    timePref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {

            if (!(Boolean) newValue) {
                return true;
            }

            DialogFactory.TimeDialogListener startTimeListener = new DialogFactory.TimeDialogListener() {

                @Override
                public void onTimeSet(TimePicker view, int hour, int minute) {
                    startHour = hour;
                    startMinute = minute;

                    DialogFactory.TimeDialogListener endTimeListener = new DialogFactory.TimeDialogListener() {
                        @Override
                        public void onTimeSet(TimePicker view, int hour, int minute) {
                            endHour = hour;
                            endMinute = minute;

                            timePref.setSummary(String.format("Time active: %02d:%02d - %02d:%02d", startHour,
                                    startMinute, endHour, endMinute));

                        }
                    };

                    DialogFactory.showTimeDialog(appContext, "End time?", endTimeListener, startHour,
                            startMinute);

                }
            };

            DialogFactory.showTimeDialog(appContext, "Start time?", startTimeListener, startHour, startMinute);

            return true;
        }
    });

    if (savedInstanceState != null) {

        if (sourcePosition == -1) {
            sourceSpinner
                    .setSelection(getPositionOfType(savedInstanceState.getString("type", AppSettings.WEBSITE)));
        }

    }

    if (sourcePosition == -1) {
        sourceImage.setVisibility(View.GONE);
        sourceSpinnerText.setVisibility(View.VISIBLE);
        sourceSpinner.setVisibility(View.VISIBLE);

        SourceSpinnerAdapter adapter = new SourceSpinnerAdapter(appContext, R.layout.spinner_row,
                Arrays.asList(getResources().getStringArray(R.array.source_menu)));
        sourceSpinner.setAdapter(adapter);
        sourceSpinner.setSelection(0);
        sourceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                selectSource(position);
                Log.i(TAG, "Spinner launched folder fragment");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        type = AppSettings.WEBSITE;
        hint = "URL";
        prefix = "";
        suffix = "";

        startHour = 0;
        startMinute = 0;
        endHour = 0;
        endMinute = 0;
    } else {
        sourceImage.setVisibility(View.VISIBLE);
        sourceSpinnerText.setVisibility(View.GONE);
        sourceSpinner.setVisibility(View.GONE);

        type = arguments.getString("type");

        folderData = arguments.getString("data");
        String data = folderData;

        hint = AppSettings.getSourceDataHint(type);
        prefix = AppSettings.getSourceDataPrefix(type);
        suffix = "";

        switch (type) {
        case AppSettings.GOOGLE_ALBUM:
            sourceTitle.setFocusable(false);
            sourceData.setFocusable(false);
            sourceNum.setFocusable(false);
        case AppSettings.FOLDER:
            data = Arrays.toString(folderData.split(AppSettings.DATA_SPLITTER));
            break;
        case AppSettings.TUMBLR_BLOG:
            suffix = ".tumblr.com";
            break;

        }

        sourceTitle.setText(arguments.getString("title"));
        sourceNum.setText("" + arguments.getInt("num"));
        sourceData.setText(data);

        if (imageDrawable != null) {
            sourceImage.setImageDrawable(imageDrawable);
        }

        boolean showPreview = arguments.getBoolean("preview");
        if (showPreview) {
            sourceImage.setVisibility(View.VISIBLE);
        }

        ((CustomSwitchPreference) findPreference("source_show_preview")).setChecked(showPreview);

        String[] timeArray = arguments.getString("time").split(":|[ -]+");

        try {
            startHour = Integer.parseInt(timeArray[0]);
            startMinute = Integer.parseInt(timeArray[1]);
            endHour = Integer.parseInt(timeArray[2]);
            endMinute = Integer.parseInt(timeArray[3]);
            timePref.setSummary(String.format("Time active: %02d:%02d - %02d:%02d", startHour, startMinute,
                    endHour, endMinute));
        } catch (NumberFormatException e) {
            e.printStackTrace();
            startHour = 0;
            startMinute = 0;
            endHour = 0;
            endMinute = 0;
        }

    }

    setDataWrappers();

    sourceUse = (Switch) headerView.findViewById(R.id.source_use_switch);
    sourceUse.setChecked(arguments.getBoolean("use"));

    if (AppSettings.getTheme().equals(AppSettings.APP_LIGHT_THEME)) {
        view.setBackgroundColor(getResources().getColor(R.color.LIGHT_THEME_BACKGROUND));
    } else {
        view.setBackgroundColor(getResources().getColor(R.color.DARK_THEME_BACKGROUND));
    }

    ListView listView = (ListView) view.findViewById(android.R.id.list);
    listView.addHeaderView(headerView);

    if (savedInstanceState != null) {
        sourceTitle.setText(savedInstanceState.getString("title", ""));
        sourceData.setText(savedInstanceState.getString("data", ""));
        sourceNum.setText(savedInstanceState.getString("num", ""));
    }

    return view;
}

From source file:kr.wdream.ui.ChatActivity.java

private void updateVisibleRows() {
    if (chatListView == null) {
        return;/*  w  ww  .j ava2s. c om*/
    }
    int count = chatListView.getChildCount();
    MessageObject editingMessageObject = chatActivityEnterView != null
            ? chatActivityEnterView.getEditingMessageObject()
            : null;
    for (int a = 0; a < count; a++) {
        View view = chatListView.getChildAt(a);
        if (view instanceof ChatMessageCell) {
            ChatMessageCell cell = (ChatMessageCell) view;

            boolean disableSelection = false;
            boolean selected = false;
            if (actionBar.isActionModeShowed()) {
                MessageObject messageObject = cell.getMessageObject();
                if (messageObject == editingMessageObject
                        || selectedMessagesIds[messageObject.getDialogId() == dialog_id ? 0 : 1]
                                .containsKey(messageObject.getId())) {
                    view.setBackgroundColor(Theme.MSG_SELECTED_BACKGROUND_COLOR);
                    selected = true;
                } else {
                    view.setBackgroundColor(0);
                }
                disableSelection = true;
            } else {
                view.setBackgroundColor(0);
            }

            cell.setMessageObject(cell.getMessageObject());
            cell.setCheckPressed(!disableSelection, disableSelection && selected);
            cell.setHighlighted(highlightMessageId != Integer.MAX_VALUE && cell.getMessageObject() != null
                    && cell.getMessageObject().getId() == highlightMessageId);
            if (searchContainer != null && searchContainer.getVisibility() == View.VISIBLE
                    && MessagesSearchQuery.getLastSearchQuery() != null) {
                cell.setHighlightedText(MessagesSearchQuery.getLastSearchQuery());
            } else {
                cell.setHighlightedText(null);
            }
        } else if (view instanceof ChatActionCell) {
            ChatActionCell cell = (ChatActionCell) view;
            cell.setMessageObject(cell.getMessageObject());
        }
    }
}

From source file:org.sirimangalo.meditationplus.AdapterCommit.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.list_item_commit, parent, false);

    final View shell = rowView.findViewById(R.id.detail_shell);

    rowView.setOnClickListener(new View.OnClickListener() {
        @Override//from  w  ww  .j  a  va  2s.c  om
        public void onClick(View view) {
            boolean visible = shell.getVisibility() == View.VISIBLE;

            shell.setVisibility(visible ? View.GONE : View.VISIBLE);

            context.setCommitVisible(position, !visible);

        }
    });

    final JSONObject p = values.get(position);

    TextView title = (TextView) rowView.findViewById(R.id.title);
    TextView descV = (TextView) rowView.findViewById(R.id.desc);
    TextView defV = (TextView) rowView.findViewById(R.id.def);
    TextView usersV = (TextView) rowView.findViewById(R.id.users);
    TextView youV = (TextView) rowView.findViewById(R.id.you);

    try {

        if (p.getBoolean("open"))
            shell.setVisibility(View.VISIBLE);

        title.setText(p.getString("title"));
        descV.setText(p.getString("description"));

        String length = p.getString("length");
        String time = p.getString("time");
        final String cid = p.getString("cid");

        String def = "";

        boolean repeat = false;

        if (length.indexOf(":") > 0) {
            repeat = true;
            String[] lengtha = length.split(":");
            def += lengtha[0] + " minutes walking and " + lengtha[1] + " minutes sitting";
        } else
            def += length + " minutes total meditation";

        String period = p.getString("period");

        String day = p.getString("day");

        if (period.equals("daily")) {
            if (repeat)
                def += " every day";
            else
                def += " per day";
        } else if (period.equals("weekly")) {
            if (repeat)
                def += " every " + dow[Integer.parseInt(day)];
            else
                def += " per week";
        } else if (period.equals("monthly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the month";
            else
                def += " per month";
        } else if (period.equals("yearly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the year";
            else
                def += " per year";
        }

        if (!time.equals("any")) {
            Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            utc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
            utc.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));

            Calendar here = Calendar.getInstance();
            here.setTimeInMillis(utc.getTimeInMillis());

            int hours = here.get(Calendar.HOUR_OF_DAY);
            int minutes = here.get(Calendar.MINUTE);

            def += " at " + (time.length() == 4 ? "0" : "") + time.replace(":", "") + "h UTC <i>("
                    + (hours > 12 ? hours - 12 : hours) + ":" + ((minutes < 10 ? "0" : "") + minutes) + " "
                    + (hours > 11 && hours < 24 ? "PM" : "AM") + " your time)</i>";
        }

        defV.setText(Html.fromHtml(def));

        JSONObject usersJ = p.getJSONObject("users");

        ArrayList<String> committedArray = new ArrayList<String>();

        // collect into array

        for (int i = 0; i < usersJ.names().length(); i++) {
            try {
                String j = usersJ.names().getString(i);
                String k = j;
                //                    if(j.equals(p.getString("creator")))
                //                        k = "["+j+"]";
                committedArray.add(k);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        String text = context.getString(R.string.committed) + " ";

        // add spans

        int committed = -1;

        int pos = text.length(); // start after "Committed: "

        text += TextUtils.join(", ", committedArray);
        Spannable span = new SpannableString(text);

        span.setSpan(new StyleSpan(Typeface.BOLD), 0, pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // bold the "Online: "

        for (int i = 0; i < committedArray.size(); i++) {
            try {

                final String oneCom = committedArray.get(i);
                String userCom = usersJ.getString(oneCom);
                //String userCom = usersJ.getString(oneCom.replace("[", "").replace("]", ""));

                //if(oneCom.replace("[","").replace("]","").equals(loggedUser))
                if (oneCom.equals(loggedUser))
                    committed = Integer.parseInt(userCom);

                int end = pos + oneCom.length();

                ClickableSpan clickable = new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        context.showProfile(oneCom);
                    }

                };
                span.setSpan(clickable, pos, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                span.setSpan(new UnderlineSpan() {
                    public void updateDrawState(TextPaint tp) {
                        tp.setUnderlineText(false);
                    }
                }, pos, end, 0);

                String color = Utils.makeRedGreen(Integer.parseInt(userCom), true);

                span.setSpan(new ForegroundColorSpan(Color.parseColor("#FF" + color)), pos, end,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                pos += oneCom.length() + 2;

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        usersV.setText(span);
        usersV.setMovementMethod(new LinkMovementMethod());

        if (loggedUser != null && loggedUser.length() > 0) {
            LinearLayout bl = (LinearLayout) rowView.findViewById(R.id.commit_buttons);
            if (!usersJ.has(loggedUser)) {
                Button commitB = new Button(context);
                commitB.setId(R.id.commit_button);
                commitB.setText(R.string.commit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("commitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            } else {
                Button commitB = new Button(context);
                commitB.setId(R.id.uncommit_button);
                commitB.setText(R.string.uncommit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("uncommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            }

            if (loggedUser.equals(p.getString("creator")) || context.isAdmin) {
                Button commitB2 = new Button(context);
                commitB2.setId(R.id.edit_commit_button);
                commitB2.setText(R.string.edit);
                commitB2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(context, ActivityCommit.class);
                        i.putExtra("commitment", p.toString());
                        context.startActivity(i);
                    }
                });
                bl.addView(commitB2);

                Button commitB3 = new Button(context);
                commitB3.setId(R.id.uncommit_button);
                commitB3.setText(R.string.delete);
                commitB3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("delcommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB3);
            }

        }

        if (committed > -1) {
            int color = Color.parseColor("#FF" + Utils.makeRedGreen(committed, false));
            rowView.setBackgroundColor(color);
        }

        if (committed != -1) {
            youV.setText(String.format(context.getString(R.string.you_commit_x), committed));
            youV.setVisibility(View.VISIBLE);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return rowView;
}

From source file:com.kenmeidearu.materialdatetimepicker.date.DatePickerDialog.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // All options have been set at this point: round the initial selection if necessary
    setToNearestDate(mCalendar);/*  ww w. j  a va 2  s .c o m*/

    View view = inflater.inflate(R.layout.mdtp_date_picker_dialog, container, false);
    timeDisplayView = (RelativeLayout) view.findViewById(R.id.time_display);
    mDayOfWeekView = (TextView) view.findViewById(R.id.date_picker_header);
    mMonthAndDayView = (LinearLayout) view.findViewById(R.id.date_picker_month_and_year);
    mSelectedMonthTextView = (TextView) view.findViewById(R.id.date_picker_month);
    mSelectedMonthTextView.setOnClickListener(this);
    mSelectedDayTextView = (TextView) view.findViewById(R.id.date_picker_day);
    mSelectedDayTextView.setOnClickListener(this);

    mYearView = (TextView) view.findViewById(R.id.date_picker_year);
    mYearView.setOnClickListener(this);

    int listPosition = -1;
    int listPositionOffset = 0;
    int currentView = mDefaultView;
    if (savedInstanceState != null) {
        mWeekStart = savedInstanceState.getInt(KEY_WEEK_START);
        mMinYear = savedInstanceState.getInt(KEY_YEAR_START);
        mMaxYear = savedInstanceState.getInt(KEY_YEAR_END);
        currentView = savedInstanceState.getInt(KEY_CURRENT_VIEW);
        listPosition = savedInstanceState.getInt(KEY_LIST_POSITION);
        listPositionOffset = savedInstanceState.getInt(KEY_LIST_POSITION_OFFSET);
        mMinDate = (Calendar) savedInstanceState.getSerializable(KEY_MIN_DATE);
        mMaxDate = (Calendar) savedInstanceState.getSerializable(KEY_MAX_DATE);
        highlightedDays = (Calendar[]) savedInstanceState.getSerializable(KEY_HIGHLIGHTED_DAYS);
        selectableDays = (Calendar[]) savedInstanceState.getSerializable(KEY_SELECTABLE_DAYS);
        disabledDays = (Calendar[]) savedInstanceState.getSerializable(KEY_DISABLED_DAYS);
        mThemeDark = savedInstanceState.getBoolean(KEY_THEME_DARK);
        mThemeDarkChanged = savedInstanceState.getBoolean(KEY_THEME_DARK_CHANGED);
        mAccentColor = savedInstanceState.getInt(KEY_ACCENT);
        mVibrate = savedInstanceState.getBoolean(KEY_VIBRATE);
        mDismissOnPause = savedInstanceState.getBoolean(KEY_DISMISS);
        mAutoDismiss = savedInstanceState.getBoolean(KEY_AUTO_DISMISS);
        mTitle = savedInstanceState.getString(KEY_TITLE);
        mOkResid = savedInstanceState.getInt(KEY_OK_RESID);
        mOkString = savedInstanceState.getString(KEY_OK_STRING);
        mCancelResid = savedInstanceState.getInt(KEY_CANCEL_RESID);
        mCancelString = savedInstanceState.getString(KEY_CANCEL_STRING);
    }

    final Activity activity = getActivity();
    mDayPickerView = new SimpleDayPickerView(activity, this);
    mYearPickerView = new YearPickerView(activity, this);
    mMonthPickerView = new MonthPickerView(activity, this);
    mHourPickerView = new TimePickerView(activity, this, "HOUR", mIs24HourMode);
    mMinutePickerView = new TimePickerView(activity, this, "MINUTE", mIs24HourMode);
    mSecondPickerView = new TimePickerView(activity, this, "SECOND", mIs24HourMode);

    // if theme mode has not been set by java code, check if it is specified in Style.xml
    if (!mThemeDarkChanged) {
        mThemeDark = Utils.isDarkTheme(activity, mThemeDark);
    }

    Resources res = getResources();
    mDayPickerDescription = res.getString(R.string.mdtp_day_picker_description);
    mSelectDay = res.getString(R.string.mdtp_select_day);
    mMonthPickerDescription = res.getString(R.string.mdtp_month_picker_description);
    mSelectMonth = res.getString(R.string.mdtp_select_month);
    mYearPickerDescription = res.getString(R.string.mdtp_year_picker_description);
    mSelectYear = res.getString(R.string.mdtp_select_year);
    //add for timer dialog
    mHourPickerDescription = res.getString(R.string.mdtp_hour_picker_description);
    mSelectHours = res.getString(R.string.mdtp_select_hours);
    mMinutePickerDescription = res.getString(R.string.mdtp_minute_picker_description);
    mSelectMinutes = res.getString(R.string.mdtp_select_minutes);
    mSecondPickerDescription = res.getString(R.string.mdtp_second_picker_description);
    mSelectSeconds = res.getString(R.string.mdtp_select_seconds);

    mHourView = (TextView) view.findViewById(R.id.hours);
    mHourView.setOnClickListener(this);
    mHourSpaceView = (TextView) view.findViewById(R.id.hour_space);
    mMinuteSpaceView = (TextView) view.findViewById(R.id.minutes_space);
    mMinuteView = (TextView) view.findViewById(R.id.minutes);
    mMinuteView.setOnClickListener(this);
    mSecondSpaceView = (TextView) view.findViewById(R.id.seconds_space);
    mSecondView = (TextView) view.findViewById(R.id.seconds);
    mSecondView.setOnClickListener(this);
    mAmPmTextView = (TextView) view.findViewById(R.id.ampm_label);
    mAmPmTextView.setOnClickListener(this);
    String[] amPmTexts = new DateFormatSymbols().getAmPmStrings();
    mAmText = amPmTexts[0];
    mPmText = amPmTexts[1];

    // Enable or disable the AM/PM view.
    mAmPmHitspace = view.findViewById(R.id.ampm_hitspace);
    if (mIs24HourMode) {
        mAmPmTextView.setVisibility(View.GONE);
    } else {
        mAmPmTextView.setVisibility(View.VISIBLE);
        updateAmPmDisplay(mInitialTime.isAM() ? AM : PM);
        mAmPmHitspace.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                tryVibrate();
                int amOrPm = getIsCurrentlyAmOrPm();
                if (amOrPm == AM) {
                    amOrPm = PM;
                } else if (amOrPm == PM) {
                    amOrPm = AM;
                }
                setAmOrPm(amOrPm);
            }
        });
    }

    // Disable seconds picker
    if (!mEnableSeconds) {
        mSecondView.setVisibility(View.GONE);
        view.findViewById(R.id.separator_seconds).setVisibility(View.GONE);
    }

    // Disable minutes picker
    if (!mEnableMinutes) {
        mMinuteSpaceView.setVisibility(View.GONE);
        view.findViewById(R.id.separator).setVisibility(View.GONE);
    }

    // Center stuff depending on what's visible
    //only enable date
    if (mOnlyDate) {
        timeDisplayView.setVisibility(View.GONE);
    }
    if (mIs24HourMode && !mEnableSeconds && mEnableMinutes) {
        // center first separator
        RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        paramsSeparator.addRule(RelativeLayout.CENTER_IN_PARENT);
        TextView separatorView = (TextView) view.findViewById(R.id.separator);
        separatorView.setLayoutParams(paramsSeparator);
    } else if (!mEnableMinutes && !mEnableSeconds) {
        // center the hour
        RelativeLayout.LayoutParams paramsHour = new RelativeLayout.LayoutParams(
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        paramsHour.addRule(RelativeLayout.CENTER_IN_PARENT);
        mHourSpaceView.setLayoutParams(paramsHour);

        if (!mIs24HourMode) {
            RelativeLayout.LayoutParams paramsAmPm = new RelativeLayout.LayoutParams(
                    ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
            paramsAmPm.addRule(RelativeLayout.RIGHT_OF, R.id.hour_space);
            paramsAmPm.addRule(RelativeLayout.ALIGN_BASELINE, R.id.hour_space);
            mAmPmTextView.setLayoutParams(paramsAmPm);
        }
    } else if (mEnableSeconds) {
        // link separator to minutes
        final View separator = view.findViewById(R.id.separator);
        RelativeLayout.LayoutParams paramsSeparator = new RelativeLayout.LayoutParams(
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
        paramsSeparator.addRule(RelativeLayout.LEFT_OF, R.id.minutes_space);
        paramsSeparator.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        separator.setLayoutParams(paramsSeparator);

        if (!mIs24HourMode) {
            // center minutes
            RelativeLayout.LayoutParams paramsMinutes = new RelativeLayout.LayoutParams(
                    ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
            paramsMinutes.addRule(RelativeLayout.CENTER_IN_PARENT);
            mMinuteSpaceView.setLayoutParams(paramsMinutes);
        } else {
            // move minutes to right of center
            RelativeLayout.LayoutParams paramsMinutes = new RelativeLayout.LayoutParams(
                    ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
            paramsMinutes.addRule(RelativeLayout.RIGHT_OF, R.id.center_view);
            mMinuteSpaceView.setLayoutParams(paramsMinutes);
        }
    }

    //end timer
    int bgColorResource = mThemeDark ? R.color.mdtp_date_picker_view_animator_dark_theme
            : R.color.mdtp_date_picker_view_animator;
    view.setBackgroundColor(ContextCompat.getColor(activity, bgColorResource));

    mAnimator = (AccessibleDateAnimator) view.findViewById(R.id.animator);
    mAnimator.addView(mDayPickerView);
    mAnimator.addView(mYearPickerView);
    mAnimator.addView(mMonthPickerView);
    mAnimator.addView(mHourPickerView);
    mAnimator.addView(mMinutePickerView);
    mAnimator.addView(mSecondPickerView);
    mAnimator.setTimeMilis(mInitialTime);
    mAnimator.setDateMillis(mCalendar.getTimeInMillis());
    // TODO: Replace with animation decided upon by the design team.
    Animation animation = new AlphaAnimation(0.0f, 1.0f);
    animation.setDuration(ANIMATION_DURATION);
    mAnimator.setInAnimation(animation);
    // TODO: Replace with animation decided upon by the design team.
    Animation animation2 = new AlphaAnimation(1.0f, 0.0f);
    animation2.setDuration(ANIMATION_DURATION);
    mAnimator.setOutAnimation(animation2);

    Button okButton = (Button) view.findViewById(R.id.ok);
    okButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            tryVibrate();
            notifyOnDateListener();
            dismiss();
        }
    });
    okButton.setTypeface(TypefaceHelper.get(activity, "Roboto-Medium"));
    if (mOkString != null)
        okButton.setText(mOkString);
    else
        okButton.setText(mOkResid);

    Button cancelButton = (Button) view.findViewById(R.id.cancel);
    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            tryVibrate();
            if (getDialog() != null)
                getDialog().cancel();
        }
    });
    cancelButton.setTypeface(TypefaceHelper.get(activity, "Roboto-Medium"));
    if (mCancelString != null)
        cancelButton.setText(mCancelString);
    else
        cancelButton.setText(mCancelResid);
    cancelButton.setVisibility(isCancelable() ? View.VISIBLE : View.GONE);

    // If an accent color has not been set manually, get it from the context
    if (mAccentColor == -1) {
        mAccentColor = Utils.getAccentColorFromThemeIfAvailable(getActivity());
    }
    if (mDayOfWeekView != null)
        mDayOfWeekView.setBackgroundColor(Utils.darkenColor(mAccentColor));
    view.findViewById(R.id.day_picker_selected_date_layout).setBackgroundColor(mAccentColor);
    okButton.setTextColor(mAccentColor);
    cancelButton.setTextColor(mAccentColor);

    if (getDialog() == null) {
        view.findViewById(R.id.done_background).setVisibility(View.GONE);
    }

    updateDisplay(false);
    setCurrentView(currentView);

    if (listPosition != -1) {
        if (currentView == MONTH_AND_DAY_VIEW) {
            mDayPickerView.postSetSelection(listPosition);
        } else if (currentView == MONTH_VIEW) {
            mMonthPickerView.postSetSelectionFromTop(listPosition, listPositionOffset);
        } else if (currentView == YEAR_VIEW) {
            mYearPickerView.postSetSelectionFromTop(listPosition, listPositionOffset);
        } else if (currentView == HOUR_INDEX) {
            mHourPickerView.postSetSelectionFromTop(listPosition, listPositionOffset);
        } else if (currentView == MINUTE_INDEX) {
            mMinutePickerView.postSetSelectionFromTop(listPosition, listPositionOffset);
        } else if (currentView == SECOND_INDEX) {
            mSecondPickerView.postSetSelectionFromTop(listPosition, listPositionOffset);
        }
    }

    mHapticFeedbackController = new HapticFeedbackController(activity);
    return view;
}

From source file:net.bluehack.ui.ChatActivity.java

@Override
public View createView(Context context) {

    if (chatMessageCellsCache.isEmpty()) {
        for (int a = 0; a < 8; a++) {
            chatMessageCellsCache.add(new ChatMessageCell(context));
        }//from  www  .ja v a  2 s  . c  o  m
    }
    for (int a = 1; a >= 0; a--) {
        selectedMessagesIds[a].clear();
        selectedMessagesCanCopyIds[a].clear();
    }
    cantDeleteMessagesCount = 0;

    hasOwnBackground = true;
    if (chatAttachAlert != null) {
        chatAttachAlert.onDestroy();
        chatAttachAlert = null;
    }

    Theme.loadRecources(context);
    Theme.loadChatResources(context);

    actionBar.setAddToContainer(false);
    actionBar.setBackButtonDrawable(new BackDrawable(false));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(final int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    for (int a = 1; a >= 0; a--) {
                        selectedMessagesIds[a].clear();
                        selectedMessagesCanCopyIds[a].clear();
                    }
                    cantDeleteMessagesCount = 0;
                    if (chatActivityEnterView.isEditingMessage()) {
                        chatActivityEnterView.setEditingMessageObject(null, false);
                    } else {
                        actionBar.hideActionMode();
                        updatePinnedMessageView(true);
                    }
                    updateVisibleRows();
                } else {
                    finishFragment();
                }
            } else if (id == copy) {
                String str = "";
                int previousUid = 0;
                for (int a = 1; a >= 0; a--) {
                    ArrayList<Integer> ids = new ArrayList<>(selectedMessagesCanCopyIds[a].keySet());
                    if (currentEncryptedChat == null) {
                        Collections.sort(ids);
                    } else {
                        Collections.sort(ids, Collections.reverseOrder());
                    }
                    for (int b = 0; b < ids.size(); b++) {
                        Integer messageId = ids.get(b);
                        MessageObject messageObject = selectedMessagesCanCopyIds[a].get(messageId);
                        if (str.length() != 0) {
                            str += "\n\n";
                        }
                        str += getMessageContent(messageObject, previousUid, true);
                        previousUid = messageObject.messageOwner.from_id;
                    }
                }
                if (str.length() != 0) {
                    AndroidUtilities.addToClipboard(str);
                }
                for (int a = 1; a >= 0; a--) {
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                }
                cantDeleteMessagesCount = 0;
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == edit_done) {
                if (chatActivityEnterView != null
                        && (chatActivityEnterView.isEditingCaption() || chatActivityEnterView.hasText())) {
                    chatActivityEnterView.doneEditingMessage();
                }
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                createDeleteMessagesAlert(null);
            } else if (id == forward) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(ChatActivity.this);
                presentFragment(fragment);
            } else if (id == chat_enc_timer) {
                if (getParentActivity() == null) {
                    return;
                }
                showDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat).create());
            } else if (id == clear_history || id == delete_chat) {
                if (getParentActivity() == null) {
                    return;
                }
                final boolean isChat = (int) dialog_id < 0 && (int) (dialog_id >> 32) != 1;
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                if (id == clear_history) {
                    builder.setMessage(LocaleController.getString("AreYouSureClearHistory",
                            R.string.AreYouSureClearHistory));
                } else {
                    if (isChat) {
                        builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit",
                                R.string.AreYouSureDeleteAndExit));
                    } else {
                        builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                                R.string.AreYouSureDeleteThisChat));
                    }
                }
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (id != clear_history) {
                                    if (isChat) {
                                        if (ChatObject.isNotInChat(currentChat)) {
                                            MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                        } else {
                                            MessagesController.getInstance()
                                                    .deleteUserFromChat(
                                                            (int) -dialog_id, MessagesController.getInstance()
                                                                    .getUser(UserConfig.getClientUserId()),
                                                            null);
                                        }
                                    } else {
                                        MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                    }
                                    finishFragment();
                                } else {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 1);
                                }
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == share_contact) {
                if (currentUser == null || getParentActivity() == null) {
                    return;
                }
                if (currentUser.phone != null && currentUser.phone.length() != 0) {
                    Bundle args = new Bundle();
                    args.putInt("user_id", currentUser.id);
                    args.putBoolean("addContact", true);
                    presentFragment(new ContactAddActivity(args));
                } else {
                    shareMyContact(replyingMessageObject);
                }
            } else if (id == mute) {
                toggleMute(false);
            } else if (id == report) {
                showDialog(AlertsCreator.createReportAlert(getParentActivity(), dialog_id, ChatActivity.this));
            } else if (id == reply) {
                MessageObject messageObject = null;
                for (int a = 1; a >= 0; a--) {
                    if (messageObject == null && selectedMessagesIds[a].size() == 1) {
                        ArrayList<Integer> ids = new ArrayList<>(selectedMessagesIds[a].keySet());
                        messageObject = messagesDict[a].get(ids.get(0));
                    }
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                }
                if (messageObject != null && (messageObject.messageOwner.id > 0
                        || messageObject.messageOwner.id < 0 && currentEncryptedChat != null)) {
                    showReplyPanel(true, messageObject, null, null, false, true);
                }
                cantDeleteMessagesCount = 0;
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == chat_menu_attach) {
                if (getParentActivity() == null) {
                    return;
                }

                createChatAttachView();
                chatAttachAlert.loadGalleryPhotos();
                if (Build.VERSION.SDK_INT == 21 || Build.VERSION.SDK_INT == 22) {
                    chatActivityEnterView.closeKeyboard();
                }
                chatAttachAlert.init();
                showDialog(chatAttachAlert);
            } else if (id == bot_help) {
                SendMessagesHelper.getInstance().sendMessage("/help", dialog_id, null, null, false, null, null,
                        null);
            } else if (id == bot_settings) {
                SendMessagesHelper.getInstance().sendMessage("/settings", dialog_id, null, null, false, null,
                        null, null);
            } else if (id == search) {
                openSearchWithText(null);
            }
        }
    });

    avatarContainer = new ChatAvatarContainer(context, this, currentEncryptedChat != null);
    actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 56, 0, 40, 0));

    if (currentChat != null) {
        if (!ChatObject.isChannel(currentChat)) {
            int count = currentChat.participants_count;
            if (info != null) {
                count = info.participants.participants.size();
            }
            if (count == 0 || currentChat.deactivated || currentChat.left
                    || currentChat instanceof TLRPC.TL_chatForbidden
                    || info != null && info.participants instanceof TLRPC.TL_chatParticipantsForbidden) {
                avatarContainer.setEnabled(false);
            }
        }
    }

    ActionBarMenu menu = actionBar.createMenu();

    if (currentEncryptedChat == null && !isBroadcast) {
        searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true)
                .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

                    @Override
                    public void onSearchCollapse() {
                        avatarContainer.setVisibility(View.VISIBLE);
                        if (chatActivityEnterView.hasText()) {
                            if (headerItem != null) {
                                headerItem.setVisibility(View.GONE);
                            }
                            if (attachItem != null) {
                                attachItem.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (headerItem != null) {
                                headerItem.setVisibility(View.VISIBLE);
                            }
                            if (attachItem != null) {
                                attachItem.setVisibility(View.GONE);
                            }
                        }
                        searchItem.setVisibility(View.GONE);
                        highlightMessageId = Integer.MAX_VALUE;
                        updateVisibleRows();
                        scrollToLastMessage(false);
                        updateBottomOverlay();
                    }

                    @Override
                    public void onSearchExpand() {
                        if (!openSearchKeyboard) {
                            return;
                        }
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                searchItem.getSearchField().requestFocus();
                                AndroidUtilities.showKeyboard(searchItem.getSearchField());
                            }
                        }, 300);
                    }

                    @Override
                    public void onSearchPressed(EditText editText) {
                        updateSearchButtons(0, 0, 0);
                        MessagesSearchQuery.searchMessagesInChat(editText.getText().toString(), dialog_id,
                                mergeDialogId, classGuid, 0);
                    }
                });
        searchItem.getSearchField().setHint(LocaleController.getString("Search", R.string.Search));
        searchItem.setVisibility(View.GONE);
    }

    headerItem = menu.addItem(0, R.drawable.ic_ab_other);
    if (searchItem != null) {
        headerItem.addSubItem(search, LocaleController.getString("Search", R.string.Search), 0);
    }
    if (ChatObject.isChannel(currentChat) && !currentChat.creator
            && (!currentChat.megagroup || currentChat.username != null && currentChat.username.length() > 0)) {
        headerItem.addSubItem(report, LocaleController.getString("ReportChat", R.string.ReportChat), 0);
    }
    if (currentUser != null) {
        addContactItem = headerItem.addSubItem(share_contact, "", 0);
    }
    if (currentEncryptedChat != null) {
        timeItem2 = headerItem.addSubItem(chat_enc_timer,
                LocaleController.getString("SetTimer", R.string.SetTimer), 0);
    }
    if (!ChatObject.isChannel(currentChat)) {
        headerItem.addSubItem(clear_history, LocaleController.getString("ClearHistory", R.string.ClearHistory),
                0);
        if (currentChat != null && !isBroadcast) {
            headerItem.addSubItem(delete_chat,
                    LocaleController.getString("DeleteAndExit", R.string.DeleteAndExit), 0);
        } else {
            headerItem.addSubItem(delete_chat,
                    LocaleController.getString("DeleteChatUser", R.string.DeleteChatUser), 0);
        }
    }
    if (currentUser == null || !currentUser.self) {
        muteItem = headerItem.addSubItem(mute, null, 0);
    }
    if (currentUser != null && currentEncryptedChat == null && currentUser.bot) {
        headerItem.addSubItem(bot_settings, LocaleController.getString("BotSettings", R.string.BotSettings), 0);
        headerItem.addSubItem(bot_help, LocaleController.getString("BotHelp", R.string.BotHelp), 0);
        updateBotButtons();
    }

    updateTitle();
    avatarContainer.updateOnlineCount();
    avatarContainer.updateSubtitle();
    updateTitleIcons();

    attachItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_other).setOverrideMenuClick(true)
            .setAllowCloseAnimation(false);
    attachItem.setVisibility(View.GONE);
    menuItem = menu.addItem(chat_menu_attach, R.drawable.ic_ab_attach).setAllowCloseAnimation(false);
    menuItem.setBackgroundDrawable(null);

    actionModeViews.clear();

    final ActionBarMenu actionMode = actionBar.createActionMode();

    selectedMessagesCountTextView = new NumberTextView(actionMode.getContext());
    selectedMessagesCountTextView.setTextSize(18);
    selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    selectedMessagesCountTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionMode.addView(selectedMessagesCountTextView,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    actionModeTitleContainer = new FrameLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);

            setMeasuredDimension(width, height);

            actionModeTextView.setTextSize(!AndroidUtilities.isTablet()
                    && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 18
                            : 20);
            actionModeTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.AT_MOST));

            if (actionModeSubTextView.getVisibility() != GONE) {
                actionModeSubTextView.setTextSize(!AndroidUtilities.isTablet()
                        && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
                                ? 14
                                : 16);
                actionModeSubTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                        MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(20), MeasureSpec.AT_MOST));
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int height = bottom - top;

            int textTop;
            if (actionModeSubTextView.getVisibility() != GONE) {
                textTop = (height / 2 - actionModeTextView.getTextHeight()) / 2
                        + AndroidUtilities.dp(!AndroidUtilities.isTablet() && getResources()
                                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 2 : 3);
            } else {
                textTop = (height - actionModeTextView.getTextHeight()) / 2;
            }
            actionModeTextView.layout(0, textTop, actionModeTextView.getMeasuredWidth(),
                    textTop + actionModeTextView.getTextHeight());

            if (actionModeSubTextView.getVisibility() != GONE) {
                textTop = height / 2 + (height / 2 - actionModeSubTextView.getTextHeight()) / 2
                        - AndroidUtilities.dp(!AndroidUtilities.isTablet() && getResources()
                                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 1 : 1);
                actionModeSubTextView.layout(0, textTop, actionModeSubTextView.getMeasuredWidth(),
                        textTop + actionModeSubTextView.getTextHeight());
            }
        }
    };
    actionMode.addView(actionModeTitleContainer,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    actionModeTitleContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
    actionModeTitleContainer.setVisibility(View.GONE);

    actionModeTextView = new SimpleTextView(context);
    actionModeTextView.setTextSize(18);
    actionModeTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    actionModeTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionModeTextView.setText(LocaleController.getString("Edit", R.string.Edit));
    actionModeTitleContainer.addView(actionModeTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    actionModeSubTextView = new SimpleTextView(context);
    actionModeSubTextView.setGravity(Gravity.LEFT);
    actionModeSubTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionModeTitleContainer.addView(actionModeSubTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    if (currentEncryptedChat == null) {
        if (!isBroadcast) {
            actionModeViews.add(actionMode.addItem(reply, R.drawable.ic_ab_reply,
                    Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        }
        actionModeViews.add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(forward, R.drawable.ic_ab_fwd_forward,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(editDoneItem = actionMode.addItem(edit_done, R.drawable.check_blue,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        editDoneItem.setVisibility(View.GONE);
        editDoneItemProgress = new ContextProgressView(context, 0);
        editDoneItem.addView(editDoneItemProgress,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        editDoneItemProgress.setVisibility(View.INVISIBLE);
    } else {
        actionModeViews.add(actionMode.addItem(reply, R.drawable.ic_ab_reply,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(copy, R.drawable.ic_ab_fwd_copy,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(delete, R.drawable.ic_ab_fwd_delete,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
    }
    actionMode.getItem(copy)
            .setVisibility(selectedMessagesCanCopyIds[0].size() + selectedMessagesCanCopyIds[1].size() != 0
                    ? View.VISIBLE
                    : View.GONE);
    actionMode.getItem(delete).setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
    checkActionBarMenu();

    fragmentView = new SizeNotifierFrameLayout(context) {

        int inputFieldHeight = 0;

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == actionBar) {
                parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
            }
            return result;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);

            setMeasuredDimension(widthSize, heightSize);
            heightSize -= getPaddingTop();

            measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int actionBarHeight = actionBar.getMeasuredHeight();
            heightSize -= actionBarHeight;

            int keyboardSize = getKeyboardHeight();

            if (keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow) {
                heightSize -= chatActivityEnterView.getEmojiPadding();
            }

            int childCount = getChildCount();

            measureChildWithMargins(chatActivityEnterView, widthMeasureSpec, 0, heightMeasureSpec, 0);
            inputFieldHeight = chatActivityEnterView.getMeasuredHeight();

            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (child == null || child.getVisibility() == GONE || child == chatActivityEnterView
                        || child == actionBar) {
                    continue;
                }
                if (child == chatListView || child == progressView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec
                            .makeMeasureSpec(
                                    Math.max(AndroidUtilities.dp(10),
                                            heightSize - inputFieldHeight + AndroidUtilities.dp(
                                                    2 + (chatActivityEnterView.isTopViewVisible() ? 48 : 0))),
                                    MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == emptyViewContainer) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow) {
                        if (AndroidUtilities.isTablet()) {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                                    MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(320),
                                            heightSize - inputFieldHeight + actionBarHeight
                                                    - AndroidUtilities.statusBarHeight + getPaddingTop()),
                                            MeasureSpec.EXACTLY));
                        } else {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                                    MeasureSpec.makeMeasureSpec(
                                            heightSize - inputFieldHeight + actionBarHeight
                                                    - AndroidUtilities.statusBarHeight + getPaddingTop(),
                                            MeasureSpec.EXACTLY));
                        }
                    } else {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec
                                .makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
                    }
                } else if (child == mentionContainer) {
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mentionContainer
                            .getLayoutParams();
                    int height;
                    mentionListViewIgnoreLayout = true;

                    if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                        int size = mentionGridLayoutManager.getRowsCount(widthSize);
                        int maxHeight = size * 102;
                        if (mentionsAdapter.isBotContext()) {
                            if (mentionsAdapter.getBotContextSwitch() != null) {
                                maxHeight += 34;
                            }
                        }
                        height = heightSize - chatActivityEnterView.getMeasuredHeight()
                                + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                        mentionListView.setPadding(0,
                                Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f))), 0,
                                0);
                    } else {
                        int size = mentionsAdapter.getItemCount();
                        int maxHeight = 0;
                        if (mentionsAdapter.isBotContext()) {
                            if (mentionsAdapter.getBotContextSwitch() != null) {
                                maxHeight += 36;
                                size -= 1;
                            }
                            maxHeight += size * 68;
                        } else {
                            maxHeight += size * 36;
                        }
                        height = heightSize - chatActivityEnterView.getMeasuredHeight()
                                + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                        mentionListView.setPadding(0,
                                Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f))), 0,
                                0);
                    }

                    layoutParams.height = height;
                    layoutParams.topMargin = 0;

                    mentionListViewIgnoreLayout = false;
                    child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                            MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY));
                } else {
                    measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                }
            }
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            final int count = getChildCount();

            int paddingBottom = getKeyboardHeight() <= AndroidUtilities.dp(20)
                    && !AndroidUtilities.isInMultiwindow ? chatActivityEnterView.getEmojiPadding() : 0;
            setBottomClip(paddingBottom);

            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child.getVisibility() == GONE) {
                    continue;
                }
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;

                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = Gravity.TOP | Gravity.LEFT;
                }

                final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                case Gravity.CENTER_HORIZONTAL:
                    childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
                    break;
                case Gravity.RIGHT:
                    childLeft = r - width - lp.rightMargin;
                    break;
                case Gravity.LEFT:
                default:
                    childLeft = lp.leftMargin;
                }

                switch (verticalGravity) {
                case Gravity.TOP:
                    childTop = lp.topMargin + getPaddingTop();
                    if (child != actionBar) {
                        childTop += actionBar.getMeasuredHeight();
                    }
                    break;
                case Gravity.CENTER_VERTICAL:
                    childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
                    break;
                case Gravity.BOTTOM:
                    childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
                    break;
                default:
                    childTop = lp.topMargin;
                }

                if (child == mentionContainer) {
                    childTop -= chatActivityEnterView.getMeasuredHeight() - AndroidUtilities.dp(2);
                } else if (child == pagedownButton) {
                    childTop -= chatActivityEnterView.getMeasuredHeight();
                } else if (child == emptyViewContainer) {
                    childTop -= inputFieldHeight / 2 - actionBar.getMeasuredHeight() / 2;
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow) {
                        childTop = chatActivityEnterView.getTop() - child.getMeasuredHeight()
                                + AndroidUtilities.dp(1);
                    } else {
                        childTop = chatActivityEnterView.getBottom();
                    }
                } else if (child == gifHintTextView) {
                    childTop -= inputFieldHeight;
                } else if (child == chatListView || child == progressView) {
                    if (chatActivityEnterView.isTopViewVisible()) {
                        childTop -= AndroidUtilities.dp(48);
                    }
                } else if (child == actionBar) {
                    childTop -= getPaddingTop();
                }
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }

            updateMessagesVisisblePart();
            notifyHeightChanged();
        }
    };

    SizeNotifierFrameLayout contentView = (SizeNotifierFrameLayout) fragmentView;

    contentView.setBackgroundImage(ApplicationLoader.getCachedWallpaper());

    emptyViewContainer = new FrameLayout(context);
    emptyViewContainer.setVisibility(View.INVISIBLE);
    contentView.addView(emptyViewContainer,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    emptyViewContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    if (currentEncryptedChat == null) {
        if (currentUser != null && currentUser.self) {
            bigEmptyView = new ChatBigEmptyView(context, false);
            emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                    LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        } else {
            TextView emptyView = new TextView(context);
            if (currentUser != null && currentUser.id != 777000 && currentUser.id != 429000
                    && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) {
                emptyView.setText(LocaleController.getString("GotAQuestion", R.string.GotAQuestion));
            } else {
                emptyView.setText(LocaleController.getString("NoMessages", R.string.NoMessages));
            }
            emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
            emptyView.setGravity(Gravity.CENTER);
            emptyView.setTextColor(Theme.CHAT_EMPTY_VIEW_TEXT_COLOR);
            emptyView.setBackgroundResource(R.drawable.system);
            emptyView.getBackground().setColorFilter(Theme.colorFilter);
            emptyView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            emptyView.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(2), AndroidUtilities.dp(10),
                    AndroidUtilities.dp(3));
            emptyViewContainer.addView(emptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                    LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        }
    } else {
        bigEmptyView = new ChatBigEmptyView(context, true);
        if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) {
            bigEmptyView.setSecretText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing",
                    R.string.EncryptedPlaceholderTitleOutgoing, UserObject.getFirstName(currentUser)));
        } else {
            bigEmptyView.setSecretText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming",
                    R.string.EncryptedPlaceholderTitleIncoming, UserObject.getFirstName(currentUser)));
        }
        emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    }

    if (chatActivityEnterView != null) {
        chatActivityEnterView.onDestroy();
    }
    if (mentionsAdapter != null) {
        mentionsAdapter.onDestroy();
    }

    chatListView = new RecyclerListView(context) {
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            forceScrollToTop = false;
            if (chatAdapter.isBot) {
                int childCount = getChildCount();
                for (int a = 0; a < childCount; a++) {
                    View child = getChildAt(a);
                    if (child instanceof BotHelpCell) {
                        int height = b - t;
                        int top = height / 2 - child.getMeasuredHeight() / 2;
                        if (child.getTop() > top) {
                            child.layout(0, top, r - l, top + child.getMeasuredHeight());
                        }
                        break;
                    }
                }
            }
        }
    };
    chatListView.setTag(1);
    chatListView.setVerticalScrollBarEnabled(true);
    chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context));
    chatListView.setClipToPadding(false);
    chatListView.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(3));
    chatListView.setItemAnimator(null);
    chatListView.setLayoutAnimation(null);
    chatLayoutManager = new LinearLayoutManager(context) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    chatLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    chatLayoutManager.setStackFromEnd(true);
    chatListView.setLayoutManager(chatLayoutManager);
    contentView.addView(chatListView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    chatListView.setOnItemLongClickListener(onItemLongClickListener);
    chatListView.setOnItemClickListener(onItemClickListener);
    chatListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        private float totalDy = 0;
        private final int scrollValue = AndroidUtilities.dp(100);

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING && highlightMessageId != Integer.MAX_VALUE) {
                highlightMessageId = Integer.MAX_VALUE;
                updateVisibleRows();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            checkScrollForLoad(true);
            int firstVisibleItem = chatLayoutManager.findFirstVisibleItemPosition();
            int visibleItemCount = firstVisibleItem == RecyclerView.NO_POSITION ? 0
                    : Math.abs(chatLayoutManager.findLastVisibleItemPosition() - firstVisibleItem) + 1;
            if (visibleItemCount > 0) {
                int totalItemCount = chatAdapter.getItemCount();
                if (firstVisibleItem + visibleItemCount == totalItemCount && forwardEndReached[0]) {
                    showPagedownButton(false, true);
                } else {
                    if (dy > 0) {
                        if (pagedownButton.getTag() == null) {
                            totalDy += dy;
                            if (totalDy > scrollValue) {
                                totalDy = 0;
                                showPagedownButton(true, true);
                                pagedownButtonShowedByScroll = true;
                            }
                        }
                    } else {
                        if (pagedownButtonShowedByScroll && pagedownButton.getTag() != null) {
                            totalDy += dy;
                            if (totalDy < -scrollValue) {
                                showPagedownButton(false, true);
                                totalDy = 0;
                            }
                        }
                    }
                }
            }
            updateMessagesVisisblePart();
        }
    });
    chatListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) {
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL
                        || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            chatListView.setOnItemClickListener(onItemClickListener);
                        }
                    }, 150);
                    if (openSecretPhotoRunnable != null) {
                        AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                        openSecretPhotoRunnable = null;
                        try {
                            Toast.makeText(v.getContext(),
                                    LocaleController.getString("PhotoTip", R.string.PhotoTip),
                                    Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                    } else if (SecretPhotoViewer.getInstance().isVisible()) {
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                chatListView.setOnItemLongClickListener(onItemLongClickListener);
                                chatListView.setLongClickable(true);
                            }
                        });
                        SecretPhotoViewer.getInstance().closePhoto();
                    }
                } else if (event.getAction() != MotionEvent.ACTION_DOWN) {
                    if (SecretPhotoViewer.getInstance().isVisible()) {
                        return true;
                    } else if (openSecretPhotoRunnable != null) {
                        if (event.getAction() == MotionEvent.ACTION_MOVE) {
                            if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities
                                    .dp(5)) {
                                AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                                openSecretPhotoRunnable = null;
                            }
                        } else {
                            AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                            openSecretPhotoRunnable = null;
                        }
                        chatListView.setOnItemClickListener(onItemClickListener);
                        chatListView.setOnItemLongClickListener(onItemLongClickListener);
                        chatListView.setLongClickable(true);
                    }
                }
            }
            return false;
        }
    });
    chatListView.setOnInterceptTouchListener(new RecyclerListView.OnInterceptTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            if (chatActivityEnterView != null && chatActivityEnterView.isEditingMessage()) {
                return true;
            }
            if (actionBar.isActionModeShowed()) {
                return false;
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                int count = chatListView.getChildCount();
                for (int a = 0; a < count; a++) {
                    View view = chatListView.getChildAt(a);
                    int top = view.getTop();
                    int bottom = view.getBottom();
                    if (top > y || bottom < y) {
                        continue;
                    }
                    if (!(view instanceof ChatMessageCell)) {
                        break;
                    }
                    final ChatMessageCell cell = (ChatMessageCell) view;
                    final MessageObject messageObject = cell.getMessageObject();
                    if (messageObject == null || messageObject.isSending() || !messageObject.isSecretPhoto()
                            || !cell.getPhotoImage().isInsideImage(x, y - top)) {
                        break;
                    }
                    File file = FileLoader.getPathToMessage(messageObject.messageOwner);
                    if (!file.exists()) {
                        break;
                    }
                    startX = x;
                    startY = y;
                    chatListView.setOnItemClickListener(null);
                    openSecretPhotoRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (openSecretPhotoRunnable == null) {
                                return;
                            }
                            chatListView.requestDisallowInterceptTouchEvent(true);
                            chatListView.setOnItemLongClickListener(null);
                            chatListView.setLongClickable(false);
                            openSecretPhotoRunnable = null;
                            if (sendSecretMessageRead(messageObject)) {
                                cell.invalidate();
                            }
                            SecretPhotoViewer.getInstance().setParentActivity(getParentActivity());
                            SecretPhotoViewer.getInstance().openPhoto(messageObject);
                        }
                    };
                    AndroidUtilities.runOnUIThread(openSecretPhotoRunnable, 100);
                    return true;
                }
            }
            return false;
        }
    });

    progressView = new FrameLayout(context);
    progressView.setVisibility(View.INVISIBLE);
    contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));

    View view = new View(context);
    view.setBackgroundResource(R.drawable.system_loader);
    view.getBackground().setColorFilter(Theme.colorFilter);
    progressView.addView(view, LayoutHelper.createFrame(36, 36, Gravity.CENTER));

    ProgressBar progressBar = new ProgressBar(context);
    try {
        progressBar.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.loading_animation));
    } catch (Exception e) {
        //don't promt
    }
    progressBar.setIndeterminate(true);
    AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500);
    progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));

    if (ChatObject.isChannel(currentChat)) {
        pinnedMessageView = new FrameLayout(context);
        pinnedMessageView.setTag(1);
        pinnedMessageView.setTranslationY(-AndroidUtilities.dp(50));
        pinnedMessageView.setVisibility(View.GONE);
        pinnedMessageView.setBackgroundResource(R.drawable.blockpanel);
        contentView.addView(pinnedMessageView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
        pinnedMessageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToMessageId(info.pinned_msg_id, 0, true, 0);
            }
        });

        View lineView = new View(context);
        lineView.setBackgroundColor(0xff6c9fd2);
        pinnedMessageView.addView(lineView,
                LayoutHelper.createFrame(2, 32, Gravity.LEFT | Gravity.TOP, 8, 8, 0, 0));

        pinnedMessageImageView = new BackupImageView(context);
        pinnedMessageView.addView(pinnedMessageImageView,
                LayoutHelper.createFrame(32, 32, Gravity.TOP | Gravity.LEFT, 17, 8, 0, 0));

        pinnedMessageNameTextView = new SimpleTextView(context);
        pinnedMessageNameTextView.setTextSize(14);
        pinnedMessageNameTextView.setTextColor(Theme.PINNED_PANEL_NAME_TEXT_COLOR);
        pinnedMessageNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        pinnedMessageView.addView(pinnedMessageNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                AndroidUtilities.dp(18), Gravity.TOP | Gravity.LEFT, 18, 7.3f, 52, 0));

        pinnedMessageTextView = new SimpleTextView(context);
        pinnedMessageTextView.setTextSize(14);
        pinnedMessageTextView.setTextColor(Theme.PINNED_PANEL_MESSAGE_TEXT_COLOR);
        pinnedMessageView.addView(pinnedMessageTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                AndroidUtilities.dp(18), Gravity.TOP | Gravity.LEFT, 18, 25.3f, 52, 0));

        ImageView closePinned = new ImageView(context);
        closePinned.setImageResource(R.drawable.miniplayer_close);
        closePinned.setScaleType(ImageView.ScaleType.CENTER);
        pinnedMessageView.addView(closePinned, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
        closePinned.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getParentActivity() == null) {
                    return;
                }
                if (currentChat.creator || currentChat.editor) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(
                            LocaleController.getString("UnpinMessageAlert", R.string.UnpinMessageAlert));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().pinChannelMessage(currentChat, 0, false);
                                }
                            });
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    SharedPreferences preferences = ApplicationLoader.applicationContext
                            .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                    preferences.edit().putInt("pin_" + dialog_id, info.pinned_msg_id).commit();
                    updatePinnedMessageView(true);
                }
            }
        });
    }

    reportSpamView = new LinearLayout(context);
    reportSpamView.setTag(1);
    reportSpamView.setTranslationY(-AndroidUtilities.dp(50));
    reportSpamView.setVisibility(View.GONE);
    reportSpamView.setBackgroundResource(R.drawable.blockpanel);
    contentView.addView(reportSpamView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));

    addToContactsButton = new TextView(context);
    addToContactsButton.setTextColor(Theme.CHAT_ADD_CONTACT_TEXT_COLOR);
    addToContactsButton.setVisibility(View.GONE);
    addToContactsButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    addToContactsButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    addToContactsButton.setSingleLine(true);
    addToContactsButton.setMaxLines(1);
    addToContactsButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
    addToContactsButton.setGravity(Gravity.CENTER);
    addToContactsButton.setText(LocaleController.getString("AddContactChat", R.string.AddContactChat));
    reportSpamView.addView(addToContactsButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, 0.5f, Gravity.LEFT | Gravity.TOP, 0, 0, 0, AndroidUtilities.dp(1)));
    addToContactsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bundle args = new Bundle();
            args.putInt("user_id", currentUser.id);
            args.putBoolean("addContact", true);
            presentFragment(new ContactAddActivity(args));
        }
    });

    reportSpamContainer = new FrameLayout(context);
    reportSpamView.addView(reportSpamContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, 1.0f, Gravity.LEFT | Gravity.TOP, 0, 0, 0, AndroidUtilities.dp(1)));

    reportSpamButton = new TextView(context);
    reportSpamButton.setTextColor(Theme.CHAT_REPORT_SPAM_TEXT_COLOR);
    reportSpamButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    reportSpamButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    reportSpamButton.setSingleLine(true);
    reportSpamButton.setMaxLines(1);
    if (currentChat != null) {
        reportSpamButton.setText(LocaleController.getString("ReportSpamAndLeave", R.string.ReportSpamAndLeave));
    } else {
        reportSpamButton.setText(LocaleController.getString("ReportSpam", R.string.ReportSpam));
    }
    reportSpamButton.setGravity(Gravity.CENTER);
    reportSpamButton.setPadding(AndroidUtilities.dp(50), 0, AndroidUtilities.dp(50), 0);
    reportSpamContainer.addView(reportSpamButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    reportSpamButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            if (ChatObject.isChannel(currentChat) && !currentChat.megagroup) {
                builder.setMessage(
                        LocaleController.getString("ReportSpamAlertChannel", R.string.ReportSpamAlertChannel));
            } else if (currentChat != null) {
                builder.setMessage(
                        LocaleController.getString("ReportSpamAlertGroup", R.string.ReportSpamAlertGroup));
            } else {
                builder.setMessage(LocaleController.getString("ReportSpamAlert", R.string.ReportSpamAlert));
            }
            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
            builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (currentUser != null) {
                                MessagesController.getInstance().blockUser(currentUser.id);
                            }
                            MessagesController.getInstance().reportSpam(dialog_id, currentUser, currentChat);
                            updateSpamView();
                            if (currentChat != null) {
                                if (ChatObject.isNotInChat(currentChat)) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                } else {
                                    MessagesController.getInstance().deleteUserFromChat((int) -dialog_id,
                                            MessagesController.getInstance()
                                                    .getUser(UserConfig.getClientUserId()),
                                            null);
                                }
                            } else {
                                MessagesController.getInstance().deleteDialog(dialog_id, 0);
                            }
                            finishFragment();
                        }
                    });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            showDialog(builder.create());
        }
    });

    ImageView closeReportSpam = new ImageView(context);
    closeReportSpam.setImageResource(R.drawable.miniplayer_close);
    closeReportSpam.setScaleType(ImageView.ScaleType.CENTER);
    reportSpamContainer.addView(closeReportSpam, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
    closeReportSpam.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MessagesController.getInstance().hideReportSpam(dialog_id, currentUser, currentChat);
            updateSpamView();
        }
    });

    alertView = new FrameLayout(context);
    alertView.setTag(1);
    alertView.setTranslationY(-AndroidUtilities.dp(50));
    alertView.setVisibility(View.GONE);
    alertView.setBackgroundResource(R.drawable.blockpanel);
    contentView.addView(alertView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));

    alertNameTextView = new TextView(context);
    alertNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertNameTextView.setTextColor(Theme.ALERT_PANEL_NAME_TEXT_COLOR);
    alertNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    alertNameTextView.setSingleLine(true);
    alertNameTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertNameTextView.setMaxLines(1);
    alertView.addView(alertNameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 5, 8, 0));

    alertTextView = new TextView(context);
    alertTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertTextView.setTextColor(Theme.ALERT_PANEL_MESSAGE_TEXT_COLOR);
    alertTextView.setSingleLine(true);
    alertTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertTextView.setMaxLines(1);
    alertView.addView(alertTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 23, 8, 0));

    if (!isBroadcast) {
        mentionContainer = new FrameLayout(context) {

            private Drawable background;

            @Override
            public void onDraw(Canvas canvas) {
                if (mentionListView.getChildCount() <= 0) {
                    return;
                }
                if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()
                        && mentionsAdapter.getBotContextSwitch() == null) {
                    background.setBounds(0, mentionListViewScrollOffsetY - AndroidUtilities.dp(4),
                            getMeasuredWidth(), getMeasuredHeight());
                } else {
                    background.setBounds(0, mentionListViewScrollOffsetY - AndroidUtilities.dp(2),
                            getMeasuredWidth(), getMeasuredHeight());
                }
                background.draw(canvas);
            }

            @Override
            public void setBackgroundResource(int resid) {
                background = getContext().getResources().getDrawable(resid);
            }

            @Override
            public void requestLayout() {
                if (mentionListViewIgnoreLayout) {
                    return;
                }
                super.requestLayout();
            }
        };
        mentionContainer.setBackgroundResource(R.drawable.compose_panel);
        mentionContainer.setVisibility(View.GONE);
        mentionContainer.setWillNotDraw(false);
        contentView.addView(mentionContainer,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));

        mentionListView = new RecyclerListView(context) {

            private int lastWidth;
            private int lastHeight;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                if (!mentionListViewIsScrolling && mentionListViewScrollOffsetY != 0
                        && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        mentionListView, 0);
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                if (!mentionListViewIsScrolling && mentionListViewScrollOffsetY != 0
                        && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
                //supress warning
                return super.onTouchEvent(event);
            }

            @Override
            public void requestLayout() {
                if (mentionListViewIgnoreLayout) {
                    return;
                }
                super.requestLayout();
            }

            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                int width = r - l;
                int height = b - t;

                int newPosition = -1;
                int newTop = 0;
                if (mentionListView != null && mentionListViewLastViewPosition >= 0 && width == lastWidth
                        && height - lastHeight != 0) {
                    newPosition = mentionListViewLastViewPosition;
                    newTop = mentionListViewLastViewTop + height - lastHeight - getPaddingTop();
                }

                super.onLayout(changed, l, t, r, b);

                if (newPosition != -1) {
                    mentionListViewIgnoreLayout = true;
                    if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                        mentionGridLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                    } else {
                        mentionLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                    }
                    super.onLayout(false, l, t, r, b);
                    mentionListViewIgnoreLayout = false;
                }

                lastHeight = height;
                lastWidth = width;
                mentionListViewUpdateLayout();
            }
        };
        mentionListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, mentionListView, 0,
                        mentionsOnItemClickListener);
            }
        });
        mentionListView.setTag(2);
        mentionLayoutManager = new LinearLayoutManager(context) {
            @Override
            public boolean supportsPredictiveItemAnimations() {
                return false;
            }
        };
        mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mentionGridLayoutManager = new ExtendedGridLayoutManager(context, 100) {

            private Size size = new Size();

            @Override
            protected Size getSizeForItem(int i) {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    i++;
                }
                Object object = mentionsAdapter.getItem(i);
                if (object instanceof TLRPC.BotInlineResult) {
                    TLRPC.BotInlineResult inlineResult = (TLRPC.BotInlineResult) object;
                    if (inlineResult.document != null) {
                        size.width = inlineResult.document.thumb != null ? inlineResult.document.thumb.w : 100;
                        size.height = inlineResult.document.thumb != null ? inlineResult.document.thumb.h : 100;
                        for (int b = 0; b < inlineResult.document.attributes.size(); b++) {
                            TLRPC.DocumentAttribute attribute = inlineResult.document.attributes.get(b);
                            if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                    || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                                size.width = attribute.w;
                                size.height = attribute.h;
                                break;
                            }
                        }
                    } else {
                        size.width = inlineResult.w;
                        size.height = inlineResult.h;
                    }
                }
                return size;
            }

            @Override
            protected int getFlowItemCount() {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    return getItemCount() - 1;
                }
                return super.getFlowItemCount();
            }
        };
        mentionGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object object = mentionsAdapter.getItem(position);
                if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                    return 100;
                } else {
                    if (mentionsAdapter.getBotContextSwitch() != null) {
                        position--;
                    }
                    return mentionGridLayoutManager.getSpanSizeForItem(position);
                }
            }
        });
        mentionListView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.left = 0;
                outRect.right = 0;
                outRect.top = 0;
                outRect.bottom = 0;
                if (parent.getLayoutManager() == mentionGridLayoutManager) {
                    int position = parent.getChildAdapterPosition(view);
                    if (mentionsAdapter.getBotContextSwitch() != null) {
                        if (position == 0) {
                            return;
                        }
                        position--;
                        if (!mentionGridLayoutManager.isFirstRow(position)) {
                            outRect.top = AndroidUtilities.dp(2);
                        }
                    } else {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = mentionGridLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            }
        });
        mentionListView.setItemAnimator(null);
        mentionListView.setLayoutAnimation(null);
        mentionListView.setClipToPadding(false);
        mentionListView.setLayoutManager(mentionLayoutManager);
        mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        mentionContainer.addView(mentionListView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

        mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, false, dialog_id,
                new MentionsAdapter.MentionsAdapterDelegate() {
                    @Override
                    public void needChangePanelVisibility(boolean show) {
                        if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                            mentionListView.setLayoutManager(mentionGridLayoutManager);
                        } else {
                            mentionListView.setLayoutManager(mentionLayoutManager);
                        }
                        if (show) {
                            if (mentionListAnimation != null) {
                                mentionListAnimation.cancel();
                                mentionListAnimation = null;
                            }

                            if (mentionContainer.getVisibility() == View.VISIBLE) {
                                mentionContainer.setAlpha(1.0f);
                                return;
                            }
                            if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                                mentionGridLayoutManager.scrollToPositionWithOffset(0, 10000);
                            } else {
                                mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
                            }
                            if (allowStickersPanel && (!mentionsAdapter.isBotContext()
                                    || (allowContextBotPanel || allowContextBotPanelSecond))) {
                                if (currentEncryptedChat != null && mentionsAdapter.isBotContext()) {
                                    SharedPreferences preferences = ApplicationLoader.applicationContext
                                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                                    if (!preferences.getBoolean("secretbot", false)) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                                getParentActivity());
                                        builder.setTitle(
                                                LocaleController.getString("AppName", R.string.AppName));
                                        builder.setMessage(
                                                LocaleController.getString("SecretChatContextBotAlert",
                                                        R.string.SecretChatContextBotAlert));
                                        builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                                null);
                                        showDialog(builder.create());
                                        preferences.edit().putBoolean("secretbot", true).commit();
                                    }
                                }
                                mentionContainer.setVisibility(View.VISIBLE);
                                mentionContainer.setTag(null);
                                mentionListAnimation = new AnimatorSet();
                                mentionListAnimation.playTogether(
                                        ObjectAnimator.ofFloat(mentionContainer, "alpha", 0.0f, 1.0f));
                                mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }

                                    @Override
                                    public void onAnimationCancel(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }
                                });
                                mentionListAnimation.setDuration(200);
                                mentionListAnimation.start();
                            } else {
                                mentionContainer.setAlpha(1.0f);
                                mentionContainer.setVisibility(View.INVISIBLE);
                            }
                        } else {
                            if (mentionListAnimation != null) {
                                mentionListAnimation.cancel();
                                mentionListAnimation = null;
                            }

                            if (mentionContainer.getVisibility() == View.GONE) {
                                return;
                            }
                            if (allowStickersPanel) {
                                mentionListAnimation = new AnimatorSet();
                                mentionListAnimation
                                        .playTogether(ObjectAnimator.ofFloat(mentionContainer, "alpha", 0.0f));
                                mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionContainer.setVisibility(View.GONE);
                                            mentionContainer.setTag(null);
                                            mentionListAnimation = null;
                                        }
                                    }

                                    @Override
                                    public void onAnimationCancel(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }
                                });
                                mentionListAnimation.setDuration(200);
                                mentionListAnimation.start();
                            } else {
                                mentionContainer.setTag(null);
                                mentionContainer.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onContextSearch(boolean searching) {
                        if (chatActivityEnterView != null) {
                            chatActivityEnterView.setCaption(mentionsAdapter.getBotCaption());
                            chatActivityEnterView.showContextProgress(searching);
                        }
                    }

                    @Override
                    public void onContextClick(TLRPC.BotInlineResult result) {
                        if (getParentActivity() == null || result.content_url == null) {
                            return;
                        }
                        if (result.type.equals("video") || result.type.equals("web_player_video")) {
                            BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                            builder.setCustomView(new WebFrameLayout(getParentActivity(), builder.create(),
                                    result.title != null ? result.title : "", result.description,
                                    result.content_url, result.content_url, result.w, result.h));
                            builder.setUseFullWidth(true);
                            showDialog(builder.create());
                        } else {
                            Browser.openUrl(getParentActivity(), result.content_url);
                        }
                    }
                }));
        if (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup) {
            mentionsAdapter.setBotInfo(botInfo);
        }
        mentionsAdapter.setParentFragment(this);
        mentionsAdapter.setChatInfo(info);
        mentionsAdapter.setNeedUsernames(currentChat != null);
        mentionsAdapter.setNeedBotContext(currentEncryptedChat == null
                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
        mentionsAdapter.setBotsCount(currentChat != null ? botsCount : 1);
        mentionListView.setOnItemClickListener(
                mentionsOnItemClickListener = new RecyclerListView.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Object object = mentionsAdapter.getItem(position);
                        int start = mentionsAdapter.getResultStartPosition();
                        int len = mentionsAdapter.getResultLength();
                        if (object instanceof TLRPC.User) {
                            TLRPC.User user = (TLRPC.User) object;
                            if (user != null) {
                                if (user.username != null) {
                                    chatActivityEnterView.replaceWithText(start, len,
                                            "@" + user.username + " ");
                                } else {
                                    String name = user.first_name;
                                    if (name == null || name.length() == 0) {
                                        name = user.last_name;
                                    }
                                    Spannable spannable = new SpannableString(name + " ");
                                    spannable.setSpan(new URLSpanUserMention("" + user.id), 0,
                                            spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    chatActivityEnterView.replaceWithText(start, len, spannable);
                                }
                            }
                        } else if (object instanceof String) {
                            if (mentionsAdapter.isBotCommands()) {
                                SendMessagesHelper.getInstance().sendMessage((String) object, dialog_id, null,
                                        null, false, null, null, null);
                                chatActivityEnterView.setFieldText("");
                            } else {
                                chatActivityEnterView.replaceWithText(start, len, object + " ");
                            }
                        } else if (object instanceof TLRPC.BotInlineResult) {
                            if (chatActivityEnterView.getFieldText() == null) {
                                return;
                            }
                            TLRPC.BotInlineResult result = (TLRPC.BotInlineResult) object;
                            if (Build.VERSION.SDK_INT >= 16 && (result.type.equals("photo")
                                    && (result.photo != null || result.content_url != null)
                                    || result.type.equals("gif")
                                            && (result.document != null || result.content_url != null)
                                    || result.type.equals("video")
                                            && (result.document != null/* || result.content_url != null*/))) {
                                ArrayList<Object> arrayList = botContextResults = new ArrayList<Object>(
                                        mentionsAdapter.getSearchResultBotContext());
                                PhotoViewer.getInstance().setParentActivity(getParentActivity());
                                PhotoViewer.getInstance().openPhotoForSelect(arrayList,
                                        mentionsAdapter.getItemPosition(position), 3, botContextProvider, null);
                            } else {
                                sendBotInlineResult(result);
                            }
                        } else if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                            processInlineBotContextPM((TLRPC.TL_inlineBotSwitchPM) object);
                        }
                    }
                });

        mentionListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
            @Override
            public boolean onItemClick(View view, int position) {
                if (getParentActivity() == null || !mentionsAdapter.isLongClickEnabled()) {
                    return false;
                }
                Object object = mentionsAdapter.getItem(position);
                if (object instanceof String) {
                    if (mentionsAdapter.isBotCommands()) {
                        if (URLSpanBotCommand.enabled) {
                            chatActivityEnterView.setFieldText("");
                            chatActivityEnterView.setCommand(null, (String) object, true,
                                    currentChat != null && currentChat.megagroup);
                            return true;
                        }
                        return false;
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                        builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                        builder.setMessage(LocaleController.getString("ClearSearch", R.string.ClearSearch));
                        builder.setPositiveButton(
                                LocaleController.getString("ClearButton", R.string.ClearButton).toUpperCase(),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        mentionsAdapter.clearRecentHashtags();
                                    }
                                });
                        builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                        showDialog(builder.create());
                        return true;
                    }
                }
                return false;
            }
        });

        mentionListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                mentionListViewIsScrolling = newState == RecyclerView.SCROLL_STATE_DRAGGING;
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int lastVisibleItem;
                if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                    lastVisibleItem = mentionGridLayoutManager.findLastVisibleItemPosition();
                } else {
                    lastVisibleItem = mentionLayoutManager.findLastVisibleItemPosition();
                }
                int visibleItemCount = lastVisibleItem == RecyclerView.NO_POSITION ? 0 : lastVisibleItem;
                if (visibleItemCount > 0 && lastVisibleItem > mentionsAdapter.getItemCount() - 5) {
                    mentionsAdapter.searchForContextBotForNextOffset();
                }
                mentionListViewUpdateLayout();
            }
        });
    }

    pagedownButton = new FrameLayout(context);
    pagedownButton.setVisibility(View.INVISIBLE);
    contentView.addView(pagedownButton,
            LayoutHelper.createFrame(46, 59, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 7, 5));
    pagedownButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (returnToMessageId > 0) {
                scrollToMessageId(returnToMessageId, 0, true, returnToLoadIndex);
            } else {
                scrollToLastMessage(true);
            }
        }
    });

    ImageView pagedownButtonImage = new ImageView(context);
    pagedownButtonImage.setImageResource(R.drawable.pagedown);
    pagedownButton.addView(pagedownButtonImage,
            LayoutHelper.createFrame(46, 46, Gravity.LEFT | Gravity.BOTTOM));

    pagedownButtonCounter = new TextView(context);
    pagedownButtonCounter.setVisibility(View.INVISIBLE);
    pagedownButtonCounter.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    pagedownButtonCounter.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    pagedownButtonCounter.setTextColor(0xffffffff);
    pagedownButtonCounter.setGravity(Gravity.CENTER);
    pagedownButtonCounter.setBackgroundResource(R.drawable.chat_badge);
    pagedownButtonCounter.setMinWidth(AndroidUtilities.dp(23));
    pagedownButtonCounter.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), AndroidUtilities.dp(1));
    pagedownButton.addView(pagedownButtonCounter,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 23, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

    chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true);
    chatActivityEnterView.setDialogId(dialog_id);
    chatActivityEnterView.addToAttachLayout(menuItem);
    chatActivityEnterView.setId(id_chat_compose_panel);
    chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands);
    chatActivityEnterView.setAllowStickersAndGifs(
            currentEncryptedChat == null
                    || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
            currentEncryptedChat == null
                    || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
    contentView.addView(chatActivityEnterView, contentView.getChildCount() - 1, LayoutHelper
            .createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
    chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {
        @Override
        public void onMessageSend(CharSequence message) {
            moveScrollToLastMessage();
            showReplyPanel(false, null, null, null, false, true);
            if (mentionsAdapter != null) {
                mentionsAdapter.addHashtagsFromMessage(message);
            }
        }

        @Override
        public void onTextChanged(final CharSequence text, boolean bigChange) {
            MediaController.getInstance().setInputFieldHasText(
                    text != null && text.length() != 0 || chatActivityEnterView.isEditingMessage());
            if (stickersAdapter != null && !chatActivityEnterView.isEditingMessage()) {
                stickersAdapter.loadStikersForEmoji(text);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(),
                        chatActivityEnterView.getCursorPosition(), messages);
            }
            if (waitingForCharaterEnterRunnable != null) {
                AndroidUtilities.cancelRunOnUIThread(waitingForCharaterEnterRunnable);
                waitingForCharaterEnterRunnable = null;
            }
            if (chatActivityEnterView.isMessageWebPageSearchEnabled()
                    && (!chatActivityEnterView.isEditingMessage()
                            || !chatActivityEnterView.isEditingCaption())) {
                if (bigChange) {
                    searchLinks(text, true);
                } else {
                    waitingForCharaterEnterRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (this == waitingForCharaterEnterRunnable) {
                                searchLinks(text, false);
                                waitingForCharaterEnterRunnable = null;
                            }
                        }
                    };
                    AndroidUtilities.runOnUIThread(waitingForCharaterEnterRunnable,
                            AndroidUtilities.WEB_URL == null ? 3000 : 1000);
                }
            }
        }

        @Override
        public void needSendTyping() {
            MessagesController.getInstance().sendTyping(dialog_id, 0, classGuid);
        }

        @Override
        public void onAttachButtonHidden() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.VISIBLE);
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.GONE);
            }
        }

        @Override
        public void onAttachButtonShow() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.GONE);
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onMessageEditEnd(boolean loading) {
            if (loading) {
                showEditDoneProgress(true, true);
            } else {
                mentionsAdapter.setNeedBotContext(currentEncryptedChat == null
                        || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
                chatListView.setOnItemLongClickListener(onItemLongClickListener);
                chatListView.setOnItemClickListener(onItemClickListener);
                chatListView.setClickable(true);
                chatListView.setLongClickable(true);
                mentionsAdapter.setAllowNewMentions(true);
                actionModeTitleContainer.setVisibility(View.GONE);
                selectedMessagesCountTextView.setVisibility(View.VISIBLE);
                chatActivityEnterView.setAllowStickersAndGifs(
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
                if (editingMessageObjectReqId != 0) {
                    ConnectionsManager.getInstance().cancelRequest(editingMessageObjectReqId, true);
                    editingMessageObjectReqId = 0;
                }
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            if (size < AndroidUtilities.dp(72) + ActionBar.getCurrentActionBarHeight()) {
                allowStickersPanel = false;
                if (stickersPanel.getVisibility() == View.VISIBLE) {
                    stickersPanel.setVisibility(View.INVISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.VISIBLE) {
                    mentionContainer.setVisibility(View.INVISIBLE);
                }
            } else {
                allowStickersPanel = true;
                if (stickersPanel.getVisibility() == View.INVISIBLE) {
                    stickersPanel.setVisibility(View.VISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.INVISIBLE
                        && (!mentionsAdapter.isBotContext()
                                || (allowContextBotPanel || allowContextBotPanelSecond))) {
                    mentionContainer.setVisibility(View.VISIBLE);
                    mentionContainer.setTag(null);
                }
            }

            allowContextBotPanel = !chatActivityEnterView.isPopupShowing();
            checkContextBotPanel();
        }

        @Override
        public void onStickersTab(boolean opened) {
            if (emojiButtonRed != null) {
                emojiButtonRed.setVisibility(View.GONE);
            }
            allowContextBotPanelSecond = !opened;
            checkContextBotPanel();
        }
    });

    FrameLayout replyLayout = new FrameLayout(context) {
        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            if (chatActivityEnterView != null) {
                chatActivityEnterView.invalidate();
            }
            if (getVisibility() != GONE) {
                int height = getLayoutParams().height;
                if (chatListView != null) {
                    chatListView.setTranslationY(translationY);
                }
                if (progressView != null) {
                    progressView.setTranslationY(translationY);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(translationY);
                }
                if (pagedownButton != null) {
                    pagedownButton.setTranslationY(translationY);
                }
            }
        }

        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }

        @Override
        public void setVisibility(int visibility) {
            super.setVisibility(visibility);
            if (visibility == GONE) {
                if (chatListView != null) {
                    chatListView.setTranslationY(0);
                }
                if (progressView != null) {
                    progressView.setTranslationY(0);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(0);
                }
                if (pagedownButton != null) {
                    pagedownButton
                            .setTranslationY(pagedownButton.getTag() == null ? AndroidUtilities.dp(100) : 0);
                }
            }
        }
    };
    replyLayout.setClickable(true);
    chatActivityEnterView.addTopView(replyLayout, 48);

    View lineView = new View(context);
    lineView.setBackgroundColor(0xffe8e8e8);
    replyLayout.addView(lineView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1, Gravity.BOTTOM | Gravity.LEFT));

    replyIconImageView = new ImageView(context);
    replyIconImageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(replyIconImageView, LayoutHelper.createFrame(52, 46, Gravity.TOP | Gravity.LEFT));

    ImageView imageView = new ImageView(context);
    imageView.setImageResource(R.drawable.delete_reply);
    imageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(imageView,
            LayoutHelper.createFrame(52, 46, Gravity.RIGHT | Gravity.TOP, 0, 0.5f, 0, 0));
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (forwardingMessages != null) {
                forwardingMessages.clear();
            }
            showReplyPanel(false, null, null, foundWebPage, true, true);
        }
    });

    replyNameTextView = new SimpleTextView(context);
    replyNameTextView.setTextSize(14);
    replyNameTextView.setTextColor(Theme.REPLY_PANEL_NAME_TEXT_COLOR);
    replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    replyLayout.addView(replyNameTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 6, 52, 0));

    replyObjectTextView = new SimpleTextView(context);
    replyObjectTextView.setTextSize(14);
    replyObjectTextView.setTextColor(Theme.REPLY_PANEL_MESSAGE_TEXT_COLOR);
    replyLayout.addView(replyObjectTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 52, 0));

    replyImageView = new BackupImageView(context);
    replyLayout.addView(replyImageView,
            LayoutHelper.createFrame(34, 34, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0));

    stickersPanel = new FrameLayout(context);
    stickersPanel.setVisibility(View.GONE);
    contentView.addView(stickersPanel, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 81.5f,
            Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 38));

    stickersListView = new RecyclerListView(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersListView,
                    0);
            return super.onInterceptTouchEvent(event) || result;
        }
    };
    stickersListView.setTag(3);
    stickersListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return StickerPreviewViewer.getInstance().onTouch(event, stickersListView, 0,
                    stickersOnItemClickListener);
        }
    });
    stickersListView.setDisallowInterceptTouchEvents(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    stickersListView.setLayoutManager(layoutManager);
    stickersListView.setClipToPadding(false);
    stickersListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    stickersPanel.addView(stickersListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 78));
    initStickers();

    imageView = new ImageView(context);
    imageView.setImageResource(R.drawable.stickers_back_arrow);
    stickersPanel.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 53, 0, 0, 0));

    searchContainer = new FrameLayout(context);
    searchContainer.setBackgroundResource(R.drawable.compose_panel);
    searchContainer.setVisibility(View.INVISIBLE);
    searchContainer.setFocusable(true);
    searchContainer.setFocusableInTouchMode(true);
    searchContainer.setClickable(true);
    searchContainer.setBackgroundResource(R.drawable.compose_panel);
    searchContainer.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    contentView.addView(searchContainer,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));

    searchUpButton = new ImageView(context);
    searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
    searchUpButton.setImageResource(R.drawable.search_up);
    searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48));
    searchUpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1);
        }
    });

    searchDownButton = new ImageView(context);
    searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
    searchDownButton.setImageResource(R.drawable.search_down);
    searchContainer.addView(searchDownButton,
            LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0));
    searchDownButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2);
        }
    });

    searchCountText = new SimpleTextView(context);
    searchCountText.setTextColor(Theme.CHAT_SEARCH_COUNT_TEXT_COLOR);
    searchCountText.setTextSize(15);
    searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 108, 0, 0, 0));

    bottomOverlay = new FrameLayout(context);
    bottomOverlay.setVisibility(View.INVISIBLE);
    bottomOverlay.setFocusable(true);
    bottomOverlay.setFocusableInTouchMode(true);
    bottomOverlay.setClickable(true);
    bottomOverlay.setBackgroundResource(R.drawable.compose_panel);
    bottomOverlay.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    contentView.addView(bottomOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));

    bottomOverlayText = new TextView(context);
    bottomOverlayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    bottomOverlayText.setTextColor(Theme.CHAT_BOTTOM_OVERLAY_TEXT_COLOR);
    bottomOverlay.addView(bottomOverlayText,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    bottomOverlayChat = new FrameLayout(context);
    bottomOverlayChat.setBackgroundResource(R.drawable.compose_panel);
    bottomOverlayChat.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    bottomOverlayChat.setVisibility(View.INVISIBLE);
    contentView.addView(bottomOverlayChat,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    bottomOverlayChat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = null;
            if (currentUser != null && userBlocked) {
                if (currentUser.bot) {
                    String botUserLast = botUser;
                    botUser = null;
                    MessagesController.getInstance().unblockUser(currentUser.id);
                    if (botUserLast != null && botUserLast.length() != 0) {
                        MessagesController.getInstance().sendBotStart(currentUser, botUserLast);
                    } else {
                        SendMessagesHelper.getInstance().sendMessage("/start", dialog_id, null, null, false,
                                null, null, null);
                    }
                } else {
                    builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("AreYouSureUnblockContact",
                            R.string.AreYouSureUnblockContact));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().unblockUser(currentUser.id);
                                }
                            });
                }
            } else if (currentUser != null && currentUser.bot && botUser != null) {
                if (botUser.length() != 0) {
                    MessagesController.getInstance().sendBotStart(currentUser, botUser);
                } else {
                    SendMessagesHelper.getInstance().sendMessage("/start", dialog_id, null, null, false, null,
                            null, null);
                }
                botUser = null;
                updateBottomOverlay();
            } else {
                if (ChatObject.isChannel(currentChat) && !(currentChat instanceof TLRPC.TL_channelForbidden)) {
                    if (ChatObject.isNotInChat(currentChat)) {
                        MessagesController.getInstance().addUserToChat(currentChat.id,
                                UserConfig.getCurrentUser(), null, 0, null, null);
                    } else {
                        toggleMute(true);
                    }
                } else {
                    builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                            R.string.AreYouSureDeleteThisChat));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                    finishFragment();
                                }
                            });
                }
            }
            if (builder != null) {
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            }
        }
    });

    bottomOverlayChatText = new TextView(context);
    bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    bottomOverlayChatText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    bottomOverlayChatText.setTextColor(Theme.CHAT_BOTTOM_CHAT_OVERLAY_TEXT_COLOR);
    bottomOverlayChat.addView(bottomOverlayChatText,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    chatAdapter.updateRows();
    if (loading && messages.isEmpty()) {
        progressView.setVisibility(chatAdapter.botInfoRow == -1 ? View.VISIBLE : View.INVISIBLE);
        chatListView.setEmptyView(null);
    } else {
        progressView.setVisibility(View.INVISIBLE);
        chatListView.setEmptyView(emptyViewContainer);
    }

    chatActivityEnterView.setButtons(userBlocked ? null : botButtons);

    if (!AndroidUtilities.isTablet() || AndroidUtilities.isSmallTablet()) {
        contentView.addView(playerView = new PlayerView(context, this), LayoutHelper
                .createFrame(LayoutHelper.MATCH_PARENT, 39, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
    }

    updateContactStatus();
    updateBottomOverlay();
    updateSecretStatus();
    updateSpamView();
    updatePinnedMessageView(true);

    try {
        if (currentEncryptedChat != null && Build.VERSION.SDK_INT >= 23) {
            getParentActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
                    WindowManager.LayoutParams.FLAG_SECURE);
        }
    } catch (Throwable e) {
        FileLog.e("tmessages", e);
    }
    fixLayoutInternal();

    contentView.addView(actionBar);

    return fragmentView;
}

From source file:kr.wdream.ui.ChatActivity.java

@Override
public View createView(Context context) {

    Log.d(LOG_TAG, "createView");

    if (chatMessageCellsCache.isEmpty()) {
        for (int a = 0; a < 8; a++) {
            chatMessageCellsCache.add(new ChatMessageCell(context));
        }//from  w w w .j  a va 2s  .  com
    }
    for (int a = 1; a >= 0; a--) {
        selectedMessagesIds[a].clear();
        selectedMessagesCanCopyIds[a].clear();
    }
    cantDeleteMessagesCount = 0;

    hasOwnBackground = true;
    if (chatAttachAlert != null) {
        chatAttachAlert.onDestroy();
        chatAttachAlert = null;
    }

    Theme.loadRecources(context);
    Theme.loadChatResources(context);

    actionBar.setAddToContainer(false);
    actionBar.setBackButtonDrawable(new BackDrawable(false));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(final int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    for (int a = 1; a >= 0; a--) {
                        selectedMessagesIds[a].clear();
                        selectedMessagesCanCopyIds[a].clear();
                    }
                    cantDeleteMessagesCount = 0;
                    if (chatActivityEnterView.isEditingMessage()) {
                        chatActivityEnterView.setEditingMessageObject(null, false);
                    } else {
                        actionBar.hideActionMode();
                        updatePinnedMessageView(true);
                    }
                    updateVisibleRows();
                } else {
                    finishFragment();
                }
            } else if (id == copy) {
                String str = "";
                int previousUid = 0;
                for (int a = 1; a >= 0; a--) {
                    ArrayList<Integer> ids = new ArrayList<>(selectedMessagesCanCopyIds[a].keySet());
                    if (currentEncryptedChat == null) {
                        Collections.sort(ids);
                    } else {
                        Collections.sort(ids, Collections.reverseOrder());
                    }
                    for (int b = 0; b < ids.size(); b++) {
                        Integer messageId = ids.get(b);
                        MessageObject messageObject = selectedMessagesCanCopyIds[a].get(messageId);
                        if (str.length() != 0) {
                            str += "\n\n";
                        }
                        str += getMessageContent(messageObject, previousUid, true);
                        previousUid = messageObject.messageOwner.from_id;
                    }
                }
                if (str.length() != 0) {
                    AndroidUtilities.addToClipboard(str);
                }
                for (int a = 1; a >= 0; a--) {
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                }
                cantDeleteMessagesCount = 0;
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == edit_done) {
                if (chatActivityEnterView != null
                        && (chatActivityEnterView.isEditingCaption() || chatActivityEnterView.hasText())) {
                    chatActivityEnterView.doneEditingMessage();
                }
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                createDeleteMessagesAlert(null);
            } else if (id == forward) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(ChatActivity.this);
                presentFragment(fragment);
            } else if (id == chat_enc_timer) {
                if (getParentActivity() == null) {
                    return;
                }
                showDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat).create());
            } else if (id == clear_history || id == delete_chat) {
                if (getParentActivity() == null) {
                    return;
                }
                final boolean isChat = (int) dialog_id < 0 && (int) (dialog_id >> 32) != 1;
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                if (id == clear_history) {
                    builder.setMessage(LocaleController.getString("AreYouSureClearHistory",
                            kr.wdream.storyshop.R.string.AreYouSureClearHistory));
                } else {
                    if (isChat) {
                        builder.setMessage(LocaleController.getString("AreYouSureDeleteAndExit",
                                kr.wdream.storyshop.R.string.AreYouSureDeleteAndExit));
                    } else {
                        builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                                kr.wdream.storyshop.R.string.AreYouSureDeleteThisChat));
                    }
                }
                builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (id != clear_history) {
                                    if (isChat) {
                                        if (ChatObject.isNotInChat(currentChat)) {
                                            MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                        } else {
                                            MessagesController.getInstance()
                                                    .deleteUserFromChat(
                                                            (int) -dialog_id, MessagesController.getInstance()
                                                                    .getUser(UserConfig.getClientUserId()),
                                                            null);
                                        }
                                    } else {
                                        MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                    }
                                    finishFragment();
                                } else {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 1);
                                }
                            }
                        });
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == share_contact) {
                if (currentUser == null || getParentActivity() == null) {
                    return;
                }
                if (currentUser.phone != null && currentUser.phone.length() != 0) {
                    Bundle args = new Bundle();
                    args.putInt("user_id", currentUser.id);
                    args.putBoolean("addContact", true);
                    presentFragment(new ContactAddActivity(args));
                } else {
                    shareMyContact(replyingMessageObject);
                }
            } else if (id == mute) {
                toggleMute(false);
            } else if (id == report) {
                showDialog(AlertsCreator.createReportAlert(getParentActivity(), dialog_id, ChatActivity.this));
            } else if (id == reply) {
                MessageObject messageObject = null;
                for (int a = 1; a >= 0; a--) {
                    if (messageObject == null && selectedMessagesIds[a].size() == 1) {
                        ArrayList<Integer> ids = new ArrayList<>(selectedMessagesIds[a].keySet());
                        messageObject = messagesDict[a].get(ids.get(0));
                    }
                    selectedMessagesIds[a].clear();
                    selectedMessagesCanCopyIds[a].clear();
                }
                if (messageObject != null && (messageObject.messageOwner.id > 0
                        || messageObject.messageOwner.id < 0 && currentEncryptedChat != null)) {
                    showReplyPanel(true, messageObject, null, null, false, true);
                }
                cantDeleteMessagesCount = 0;
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            } else if (id == chat_menu_attach) {
                if (getParentActivity() == null) {
                    return;
                }

                createChatAttachView();
                chatAttachAlert.loadGalleryPhotos();
                if (Build.VERSION.SDK_INT == 21 || Build.VERSION.SDK_INT == 22) {
                    chatActivityEnterView.closeKeyboard();
                }
                chatAttachAlert.init();
                showDialog(chatAttachAlert);
            } else if (id == bot_help) {
                SendMessagesHelper.getInstance().sendMessage("/help", dialog_id, null, null, false, null, null,
                        null);
            } else if (id == bot_settings) {
                SendMessagesHelper.getInstance().sendMessage("/settings", dialog_id, null, null, false, null,
                        null, null);
            } else if (id == search) {
                openSearchWithText(null);
            }
        }
    });

    avatarContainer = new ChatAvatarContainer(context, this, currentEncryptedChat != null);
    actionBar.addView(avatarContainer, 0, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 56, 0, 40, 0));

    if (currentChat != null) {
        if (!ChatObject.isChannel(currentChat)) {
            int count = currentChat.participants_count;
            if (info != null) {
                count = info.participants.participants.size();
            }
            if (count == 0 || currentChat.deactivated || currentChat.left
                    || currentChat instanceof TLRPC.TL_chatForbidden
                    || info != null && info.participants instanceof TLRPC.TL_chatParticipantsForbidden) {
                avatarContainer.setEnabled(false);
            }
        }
    }

    ActionBarMenu menu = actionBar.createMenu();

    if (currentEncryptedChat == null && !isBroadcast) {
        searchItem = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_search).setIsSearchField(true)
                .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {

                    @Override
                    public void onSearchCollapse() {
                        avatarContainer.setVisibility(View.VISIBLE);
                        if (chatActivityEnterView.hasText()) {
                            if (headerItem != null) {
                                headerItem.setVisibility(View.GONE);
                            }
                            if (attachItem != null) {
                                attachItem.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (headerItem != null) {
                                headerItem.setVisibility(View.VISIBLE);
                            }
                            if (attachItem != null) {
                                attachItem.setVisibility(View.GONE);
                            }
                        }
                        searchItem.setVisibility(View.GONE);
                        highlightMessageId = Integer.MAX_VALUE;
                        updateVisibleRows();
                        scrollToLastMessage(false);
                        updateBottomOverlay();
                    }

                    @Override
                    public void onSearchExpand() {
                        if (!openSearchKeyboard) {
                            return;
                        }
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                searchItem.getSearchField().requestFocus();
                                AndroidUtilities.showKeyboard(searchItem.getSearchField());
                            }
                        }, 300);
                    }

                    @Override
                    public void onSearchPressed(EditText editText) {
                        updateSearchButtons(0, 0, 0);
                        MessagesSearchQuery.searchMessagesInChat(editText.getText().toString(), dialog_id,
                                mergeDialogId, classGuid, 0);
                    }
                });
        searchItem.getSearchField()
                .setHint(LocaleController.getString("Search", kr.wdream.storyshop.R.string.Search));
        searchItem.setVisibility(View.GONE);
    }

    headerItem = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_other);
    if (searchItem != null) {
        headerItem.addSubItem(search, LocaleController.getString("Search", kr.wdream.storyshop.R.string.Search),
                0);
    }
    if (ChatObject.isChannel(currentChat) && !currentChat.creator
            && (!currentChat.megagroup || currentChat.username != null && currentChat.username.length() > 0)) {
        headerItem.addSubItem(report,
                LocaleController.getString("ReportChat", kr.wdream.storyshop.R.string.ReportChat), 0);
    }
    if (currentUser != null) {
        addContactItem = headerItem.addSubItem(share_contact, "", 0);
    }
    if (currentEncryptedChat != null) {
        timeItem2 = headerItem.addSubItem(chat_enc_timer,
                LocaleController.getString("SetTimer", kr.wdream.storyshop.R.string.SetTimer), 0);
    }
    if (!ChatObject.isChannel(currentChat)) {
        headerItem.addSubItem(clear_history,
                LocaleController.getString("ClearHistory", kr.wdream.storyshop.R.string.ClearHistory), 0);
        if (currentChat != null && !isBroadcast) {
            headerItem.addSubItem(delete_chat,
                    LocaleController.getString("DeleteAndExit", kr.wdream.storyshop.R.string.DeleteAndExit), 0);
        } else {
            headerItem.addSubItem(delete_chat,
                    LocaleController.getString("DeleteChatUser", kr.wdream.storyshop.R.string.DeleteChatUser),
                    0);
        }
    }
    if (currentUser == null || !currentUser.self) {
        muteItem = headerItem.addSubItem(mute, null, 0);
    }
    if (currentUser != null && currentEncryptedChat == null && currentUser.bot) {
        headerItem.addSubItem(bot_settings,
                LocaleController.getString("BotSettings", kr.wdream.storyshop.R.string.BotSettings), 0);
        headerItem.addSubItem(bot_help,
                LocaleController.getString("BotHelp", kr.wdream.storyshop.R.string.BotHelp), 0);
        updateBotButtons();
    }

    updateTitle();
    avatarContainer.updateOnlineCount();
    avatarContainer.updateSubtitle();
    updateTitleIcons();

    attachItem = menu.addItem(chat_menu_attach, kr.wdream.storyshop.R.drawable.ic_ab_other)
            .setOverrideMenuClick(true).setAllowCloseAnimation(false);
    attachItem.setVisibility(View.GONE);
    menuItem = menu.addItem(chat_menu_attach, kr.wdream.storyshop.R.drawable.ic_ab_attach)
            .setAllowCloseAnimation(false);
    menuItem.setBackgroundDrawable(null);

    actionModeViews.clear();

    final ActionBarMenu actionMode = actionBar.createActionMode();

    selectedMessagesCountTextView = new NumberTextView(actionMode.getContext());
    selectedMessagesCountTextView.setTextSize(18);
    selectedMessagesCountTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    selectedMessagesCountTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionMode.addView(selectedMessagesCountTextView,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    selectedMessagesCountTextView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    actionModeTitleContainer = new FrameLayout(context) {

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);

            setMeasuredDimension(width, height);

            actionModeTextView.setTextSize(!AndroidUtilities.isTablet()
                    && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 18
                            : 20);
            actionModeTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                    MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(24), MeasureSpec.AT_MOST));

            if (actionModeSubTextView.getVisibility() != GONE) {
                actionModeSubTextView.setTextSize(!AndroidUtilities.isTablet()
                        && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE
                                ? 14
                                : 16);
                actionModeSubTextView.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                        MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(20), MeasureSpec.AT_MOST));
            }
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            int height = bottom - top;

            int textTop;
            if (actionModeSubTextView.getVisibility() != GONE) {
                textTop = (height / 2 - actionModeTextView.getTextHeight()) / 2
                        + AndroidUtilities.dp(!AndroidUtilities.isTablet() && getResources()
                                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 2 : 3);
            } else {
                textTop = (height - actionModeTextView.getTextHeight()) / 2;
            }
            actionModeTextView.layout(0, textTop, actionModeTextView.getMeasuredWidth(),
                    textTop + actionModeTextView.getTextHeight());

            if (actionModeSubTextView.getVisibility() != GONE) {
                textTop = height / 2 + (height / 2 - actionModeSubTextView.getTextHeight()) / 2
                        - AndroidUtilities.dp(!AndroidUtilities.isTablet() && getResources()
                                .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE ? 1 : 1);
                actionModeSubTextView.layout(0, textTop, actionModeSubTextView.getMeasuredWidth(),
                        textTop + actionModeSubTextView.getTextHeight());
            }
        }
    };
    actionMode.addView(actionModeTitleContainer,
            LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, 65, 0, 0, 0));
    actionModeTitleContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
    actionModeTitleContainer.setVisibility(View.GONE);

    actionModeTextView = new SimpleTextView(context);
    actionModeTextView.setTextSize(18);
    actionModeTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    actionModeTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionModeTextView.setText(LocaleController.getString("Edit", kr.wdream.storyshop.R.string.Edit));
    actionModeTitleContainer.addView(actionModeTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    actionModeSubTextView = new SimpleTextView(context);
    actionModeSubTextView.setGravity(Gravity.LEFT);
    actionModeSubTextView.setTextColor(Theme.ACTION_BAR_ACTION_MODE_TEXT_COLOR);
    actionModeTitleContainer.addView(actionModeSubTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    if (currentEncryptedChat == null) {
        if (!isBroadcast) {
            actionModeViews.add(actionMode.addItem(reply, kr.wdream.storyshop.R.drawable.ic_ab_reply,
                    Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        }
        actionModeViews.add(actionMode.addItem(copy, kr.wdream.storyshop.R.drawable.ic_ab_fwd_copy,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(forward, kr.wdream.storyshop.R.drawable.ic_ab_fwd_forward,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(delete, kr.wdream.storyshop.R.drawable.ic_ab_fwd_delete,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews
                .add(editDoneItem = actionMode.addItem(edit_done, kr.wdream.storyshop.R.drawable.check_blue,
                        Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        editDoneItem.setVisibility(View.GONE);
        editDoneItemProgress = new ContextProgressView(context, 0);
        editDoneItem.addView(editDoneItemProgress,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        editDoneItemProgress.setVisibility(View.INVISIBLE);
    } else {
        actionModeViews.add(actionMode.addItem(reply, kr.wdream.storyshop.R.drawable.ic_ab_reply,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(copy, kr.wdream.storyshop.R.drawable.ic_ab_fwd_copy,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
        actionModeViews.add(actionMode.addItem(delete, kr.wdream.storyshop.R.drawable.ic_ab_fwd_delete,
                Theme.ACTION_BAR_MODE_SELECTOR_COLOR, null, AndroidUtilities.dp(54)));
    }
    actionMode.getItem(copy)
            .setVisibility(selectedMessagesCanCopyIds[0].size() + selectedMessagesCanCopyIds[1].size() != 0
                    ? View.VISIBLE
                    : View.GONE);
    actionMode.getItem(delete).setVisibility(cantDeleteMessagesCount == 0 ? View.VISIBLE : View.GONE);
    checkActionBarMenu();

    fragmentView = new SizeNotifierFrameLayout(context) {

        int inputFieldHeight = 0;

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == actionBar) {
                parentLayout.drawHeaderShadow(canvas, actionBar.getMeasuredHeight());
            }
            return result;
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);

            setMeasuredDimension(widthSize, heightSize);
            heightSize -= getPaddingTop();

            measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int actionBarHeight = actionBar.getMeasuredHeight();
            heightSize -= actionBarHeight;

            int keyboardSize = getKeyboardHeight();

            if (keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow) {
                heightSize -= chatActivityEnterView.getEmojiPadding();
            }

            int childCount = getChildCount();

            measureChildWithMargins(chatActivityEnterView, widthMeasureSpec, 0, heightMeasureSpec, 0);
            inputFieldHeight = chatActivityEnterView.getMeasuredHeight();

            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (child == null || child.getVisibility() == GONE || child == chatActivityEnterView
                        || child == actionBar) {
                    continue;
                }
                if (child == chatListView || child == progressView) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec
                            .makeMeasureSpec(
                                    Math.max(AndroidUtilities.dp(10),
                                            heightSize - inputFieldHeight + AndroidUtilities.dp(
                                                    2 + (chatActivityEnterView.isTopViewVisible() ? 48 : 0))),
                                    MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (child == emptyViewContainer) {
                    int contentWidthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
                    int contentHeightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
                    child.measure(contentWidthSpec, contentHeightSpec);
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow) {
                        if (AndroidUtilities.isTablet()) {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                                    MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(320),
                                            heightSize - inputFieldHeight + actionBarHeight
                                                    - AndroidUtilities.statusBarHeight + getPaddingTop()),
                                            MeasureSpec.EXACTLY));
                        } else {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                                    MeasureSpec.makeMeasureSpec(
                                            heightSize - inputFieldHeight + actionBarHeight
                                                    - AndroidUtilities.statusBarHeight + getPaddingTop(),
                                            MeasureSpec.EXACTLY));
                        }
                    } else {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec
                                .makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
                    }
                } else if (child == mentionContainer) {
                    FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) mentionContainer
                            .getLayoutParams();
                    int height;
                    mentionListViewIgnoreLayout = true;

                    if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                        int size = mentionGridLayoutManager.getRowsCount(widthSize);
                        int maxHeight = size * 102;
                        if (mentionsAdapter.isBotContext()) {
                            if (mentionsAdapter.getBotContextSwitch() != null) {
                                maxHeight += 34;
                            }
                        }
                        height = heightSize - chatActivityEnterView.getMeasuredHeight()
                                + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                        mentionListView.setPadding(0,
                                Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f))), 0,
                                0);
                    } else {
                        int size = mentionsAdapter.getItemCount();
                        int maxHeight = 0;
                        if (mentionsAdapter.isBotContext()) {
                            if (mentionsAdapter.getBotContextSwitch() != null) {
                                maxHeight += 36;
                                size -= 1;
                            }
                            maxHeight += size * 68;
                        } else {
                            maxHeight += size * 36;
                        }
                        height = heightSize - chatActivityEnterView.getMeasuredHeight()
                                + (maxHeight != 0 ? AndroidUtilities.dp(2) : 0);
                        mentionListView.setPadding(0,
                                Math.max(0, height - AndroidUtilities.dp(Math.min(maxHeight, 68 * 1.8f))), 0,
                                0);
                    }

                    layoutParams.height = height;
                    layoutParams.topMargin = 0;

                    mentionListViewIgnoreLayout = false;
                    child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                            MeasureSpec.makeMeasureSpec(layoutParams.height, MeasureSpec.EXACTLY));
                } else {
                    measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                }
            }
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            final int count = getChildCount();

            int paddingBottom = getKeyboardHeight() <= AndroidUtilities.dp(20)
                    && !AndroidUtilities.isInMultiwindow ? chatActivityEnterView.getEmojiPadding() : 0;
            setBottomClip(paddingBottom);

            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child.getVisibility() == GONE) {
                    continue;
                }
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;

                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = Gravity.TOP | Gravity.LEFT;
                }

                final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                case Gravity.CENTER_HORIZONTAL:
                    childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
                    break;
                case Gravity.RIGHT:
                    childLeft = r - width - lp.rightMargin;
                    break;
                case Gravity.LEFT:
                default:
                    childLeft = lp.leftMargin;
                }

                switch (verticalGravity) {
                case Gravity.TOP:
                    childTop = lp.topMargin + getPaddingTop();
                    if (child != actionBar) {
                        childTop += actionBar.getMeasuredHeight();
                    }
                    break;
                case Gravity.CENTER_VERTICAL:
                    childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
                    break;
                case Gravity.BOTTOM:
                    childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
                    break;
                default:
                    childTop = lp.topMargin;
                }

                if (child == mentionContainer) {
                    childTop -= chatActivityEnterView.getMeasuredHeight() - AndroidUtilities.dp(2);
                } else if (child == pagedownButton) {
                    childTop -= chatActivityEnterView.getMeasuredHeight();
                } else if (child == emptyViewContainer) {
                    childTop -= inputFieldHeight / 2 - actionBar.getMeasuredHeight() / 2;
                } else if (chatActivityEnterView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow) {
                        childTop = chatActivityEnterView.getTop() - child.getMeasuredHeight()
                                + AndroidUtilities.dp(1);
                    } else {
                        childTop = chatActivityEnterView.getBottom();
                    }
                } else if (child == gifHintTextView) {
                    childTop -= inputFieldHeight;
                } else if (child == chatListView || child == progressView) {
                    if (chatActivityEnterView.isTopViewVisible()) {
                        childTop -= AndroidUtilities.dp(48);
                    }
                } else if (child == actionBar) {
                    childTop -= getPaddingTop();
                }
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }

            updateMessagesVisisblePart();
            notifyHeightChanged();
        }
    };

    SizeNotifierFrameLayout contentView = (SizeNotifierFrameLayout) fragmentView;

    contentView.setBackgroundImage(ApplicationLoader.getCachedWallpaper());

    emptyViewContainer = new FrameLayout(context);
    emptyViewContainer.setVisibility(View.INVISIBLE);
    contentView.addView(emptyViewContainer,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    emptyViewContainer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    if (currentEncryptedChat == null) {
        if (currentUser != null && currentUser.self) {
            bigEmptyView = new ChatBigEmptyView(context, false);
            emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                    LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        } else {
            TextView emptyView = new TextView(context);
            if (currentUser != null && currentUser.id != 777000 && currentUser.id != 429000
                    && (currentUser.id / 1000 == 333 || currentUser.id % 1000 == 0)) {
                emptyView.setText(
                        LocaleController.getString("GotAQuestion", kr.wdream.storyshop.R.string.GotAQuestion));
            } else {
                emptyView.setText(
                        LocaleController.getString("NoMessages", kr.wdream.storyshop.R.string.NoMessages));
            }
            emptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
            emptyView.setGravity(Gravity.CENTER);
            emptyView.setTextColor(Theme.CHAT_EMPTY_VIEW_TEXT_COLOR);
            emptyView.setBackgroundResource(kr.wdream.storyshop.R.drawable.system);
            emptyView.getBackground().setColorFilter(Theme.colorFilter);
            emptyView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
            emptyView.setPadding(AndroidUtilities.dp(10), AndroidUtilities.dp(2), AndroidUtilities.dp(10),
                    AndroidUtilities.dp(3));
            emptyViewContainer.addView(emptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                    LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        }
    } else {
        bigEmptyView = new ChatBigEmptyView(context, true);
        if (currentEncryptedChat.admin_id == UserConfig.getClientUserId()) {
            bigEmptyView.setSecretText(LocaleController.formatString("EncryptedPlaceholderTitleOutgoing",
                    kr.wdream.storyshop.R.string.EncryptedPlaceholderTitleOutgoing,
                    UserObject.getFirstName(currentUser)));
        } else {
            bigEmptyView.setSecretText(LocaleController.formatString("EncryptedPlaceholderTitleIncoming",
                    kr.wdream.storyshop.R.string.EncryptedPlaceholderTitleIncoming,
                    UserObject.getFirstName(currentUser)));
        }
        emptyViewContainer.addView(bigEmptyView, new FrameLayout.LayoutParams(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    }

    if (chatActivityEnterView != null) {
        chatActivityEnterView.onDestroy();
    }
    if (mentionsAdapter != null) {
        mentionsAdapter.onDestroy();
    }

    chatListView = new RecyclerListView(context) {
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            forceScrollToTop = false;
            if (chatAdapter.isBot) {
                int childCount = getChildCount();
                for (int a = 0; a < childCount; a++) {
                    View child = getChildAt(a);
                    if (child instanceof BotHelpCell) {
                        int height = b - t;
                        int top = height / 2 - child.getMeasuredHeight() / 2;
                        if (child.getTop() > top) {
                            child.layout(0, top, r - l, top + child.getMeasuredHeight());
                        }
                        break;
                    }
                }
            }
        }
    };
    chatListView.setTag(1);
    chatListView.setVerticalScrollBarEnabled(true);
    chatListView.setAdapter(chatAdapter = new ChatActivityAdapter(context));
    chatListView.setClipToPadding(false);
    chatListView.setPadding(0, AndroidUtilities.dp(4), 0, AndroidUtilities.dp(3));
    chatListView.setItemAnimator(null);
    chatListView.setLayoutAnimation(null);
    chatLayoutManager = new LinearLayoutManager(context) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    chatLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    chatLayoutManager.setStackFromEnd(true);
    chatListView.setLayoutManager(chatLayoutManager);
    contentView.addView(chatListView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    chatListView.setOnItemLongClickListener(onItemLongClickListener);
    chatListView.setOnItemClickListener(onItemClickListener);
    chatListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        private float totalDy = 0;
        private final int scrollValue = AndroidUtilities.dp(100);

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING && highlightMessageId != Integer.MAX_VALUE) {
                highlightMessageId = Integer.MAX_VALUE;
                updateVisibleRows();
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            checkScrollForLoad(true);
            int firstVisibleItem = chatLayoutManager.findFirstVisibleItemPosition();
            int visibleItemCount = firstVisibleItem == RecyclerView.NO_POSITION ? 0
                    : Math.abs(chatLayoutManager.findLastVisibleItemPosition() - firstVisibleItem) + 1;
            if (visibleItemCount > 0) {
                int totalItemCount = chatAdapter.getItemCount();
                if (firstVisibleItem + visibleItemCount == totalItemCount && forwardEndReached[0]) {
                    showPagedownButton(false, true);
                } else {
                    if (dy > 0) {
                        if (pagedownButton.getTag() == null) {
                            totalDy += dy;
                            if (totalDy > scrollValue) {
                                totalDy = 0;
                                showPagedownButton(true, true);
                                pagedownButtonShowedByScroll = true;
                            }
                        }
                    } else {
                        if (pagedownButtonShowedByScroll && pagedownButton.getTag() != null) {
                            totalDy += dy;
                            if (totalDy < -scrollValue) {
                                showPagedownButton(false, true);
                                totalDy = 0;
                            }
                        }
                    }
                }
            }
            updateMessagesVisisblePart();
        }
    });
    chatListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (openSecretPhotoRunnable != null || SecretPhotoViewer.getInstance().isVisible()) {
                if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL
                        || event.getAction() == MotionEvent.ACTION_POINTER_UP) {
                    AndroidUtilities.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            chatListView.setOnItemClickListener(onItemClickListener);
                        }
                    }, 150);
                    if (openSecretPhotoRunnable != null) {
                        AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                        openSecretPhotoRunnable = null;
                        try {
                            Toast.makeText(v.getContext(), LocaleController.getString("PhotoTip",
                                    kr.wdream.storyshop.R.string.PhotoTip), Toast.LENGTH_SHORT).show();
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                    } else if (SecretPhotoViewer.getInstance().isVisible()) {
                        AndroidUtilities.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                chatListView.setOnItemLongClickListener(onItemLongClickListener);
                                chatListView.setLongClickable(true);
                            }
                        });
                        SecretPhotoViewer.getInstance().closePhoto();
                    }
                } else if (event.getAction() != MotionEvent.ACTION_DOWN) {
                    if (SecretPhotoViewer.getInstance().isVisible()) {
                        return true;
                    } else if (openSecretPhotoRunnable != null) {
                        if (event.getAction() == MotionEvent.ACTION_MOVE) {
                            if (Math.hypot(startX - event.getX(), startY - event.getY()) > AndroidUtilities
                                    .dp(5)) {
                                AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                                openSecretPhotoRunnable = null;
                            }
                        } else {
                            AndroidUtilities.cancelRunOnUIThread(openSecretPhotoRunnable);
                            openSecretPhotoRunnable = null;
                        }
                        chatListView.setOnItemClickListener(onItemClickListener);
                        chatListView.setOnItemLongClickListener(onItemLongClickListener);
                        chatListView.setLongClickable(true);
                    }
                }
            }
            return false;
        }
    });
    chatListView.setOnInterceptTouchListener(new RecyclerListView.OnInterceptTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            if (chatActivityEnterView != null && chatActivityEnterView.isEditingMessage()) {
                return true;
            }
            if (actionBar.isActionModeShowed()) {
                return false;
            }
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                int count = chatListView.getChildCount();
                for (int a = 0; a < count; a++) {
                    View view = chatListView.getChildAt(a);
                    int top = view.getTop();
                    int bottom = view.getBottom();
                    if (top > y || bottom < y) {
                        continue;
                    }
                    if (!(view instanceof ChatMessageCell)) {
                        break;
                    }
                    final ChatMessageCell cell = (ChatMessageCell) view;
                    final MessageObject messageObject = cell.getMessageObject();
                    if (messageObject == null || messageObject.isSending() || !messageObject.isSecretPhoto()
                            || !cell.getPhotoImage().isInsideImage(x, y - top)) {
                        break;
                    }
                    File file = FileLoader.getPathToMessage(messageObject.messageOwner);
                    if (!file.exists()) {
                        break;
                    }
                    startX = x;
                    startY = y;
                    chatListView.setOnItemClickListener(null);
                    openSecretPhotoRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (openSecretPhotoRunnable == null) {
                                return;
                            }
                            chatListView.requestDisallowInterceptTouchEvent(true);
                            chatListView.setOnItemLongClickListener(null);
                            chatListView.setLongClickable(false);
                            openSecretPhotoRunnable = null;
                            if (sendSecretMessageRead(messageObject)) {
                                cell.invalidate();
                            }
                            SecretPhotoViewer.getInstance().setParentActivity(getParentActivity());
                            SecretPhotoViewer.getInstance().openPhoto(messageObject);
                        }
                    };
                    AndroidUtilities.runOnUIThread(openSecretPhotoRunnable, 100);
                    return true;
                }
            }
            return false;
        }
    });

    progressView = new FrameLayout(context);
    progressView.setVisibility(View.INVISIBLE);
    contentView.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));

    View view = new View(context);
    view.setBackgroundResource(kr.wdream.storyshop.R.drawable.system_loader);
    view.getBackground().setColorFilter(Theme.colorFilter);
    progressView.addView(view, LayoutHelper.createFrame(36, 36, Gravity.CENTER));

    ProgressBar progressBar = new ProgressBar(context);
    try {
        progressBar.setIndeterminateDrawable(
                context.getResources().getDrawable(kr.wdream.storyshop.R.drawable.loading_animation));
    } catch (Exception e) {
        //don't promt
    }
    progressBar.setIndeterminate(true);
    AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500);
    progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));

    if (ChatObject.isChannel(currentChat)) {
        pinnedMessageView = new FrameLayout(context);
        pinnedMessageView.setTag(1);
        pinnedMessageView.setTranslationY(-AndroidUtilities.dp(50));
        pinnedMessageView.setVisibility(View.GONE);
        pinnedMessageView.setBackgroundResource(kr.wdream.storyshop.R.drawable.blockpanel);
        contentView.addView(pinnedMessageView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));
        pinnedMessageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToMessageId(info.pinned_msg_id, 0, true, 0);
            }
        });

        View lineView = new View(context);
        lineView.setBackgroundColor(0xff6c9fd2);
        pinnedMessageView.addView(lineView,
                LayoutHelper.createFrame(2, 32, Gravity.LEFT | Gravity.TOP, 8, 8, 0, 0));

        pinnedMessageImageView = new BackupImageView(context);
        pinnedMessageView.addView(pinnedMessageImageView,
                LayoutHelper.createFrame(32, 32, Gravity.TOP | Gravity.LEFT, 17, 8, 0, 0));

        pinnedMessageNameTextView = new SimpleTextView(context);
        pinnedMessageNameTextView.setTextSize(14);
        pinnedMessageNameTextView.setTextColor(Theme.PINNED_PANEL_NAME_TEXT_COLOR);
        pinnedMessageNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        pinnedMessageView.addView(pinnedMessageNameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                AndroidUtilities.dp(18), Gravity.TOP | Gravity.LEFT, 18, 7.3f, 52, 0));

        pinnedMessageTextView = new SimpleTextView(context);
        pinnedMessageTextView.setTextSize(14);
        pinnedMessageTextView.setTextColor(Theme.PINNED_PANEL_MESSAGE_TEXT_COLOR);
        pinnedMessageView.addView(pinnedMessageTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                AndroidUtilities.dp(18), Gravity.TOP | Gravity.LEFT, 18, 25.3f, 52, 0));

        ImageView closePinned = new ImageView(context);
        closePinned.setImageResource(kr.wdream.storyshop.R.drawable.miniplayer_close);
        closePinned.setScaleType(ImageView.ScaleType.CENTER);
        pinnedMessageView.addView(closePinned, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
        closePinned.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getParentActivity() == null) {
                    return;
                }
                if (currentChat.creator || currentChat.editor) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("UnpinMessageAlert",
                            kr.wdream.storyshop.R.string.UnpinMessageAlert));
                    builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().pinChannelMessage(currentChat, 0, false);
                                }
                            });
                    builder.setTitle(
                            LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                    builder.setNegativeButton(
                            LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    SharedPreferences preferences = ApplicationLoader.applicationContext
                            .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
                    preferences.edit().putInt("pin_" + dialog_id, info.pinned_msg_id).commit();
                    updatePinnedMessageView(true);
                }
            }
        });
    }

    reportSpamView = new LinearLayout(context);
    reportSpamView.setTag(1);
    reportSpamView.setTranslationY(-AndroidUtilities.dp(50));
    reportSpamView.setVisibility(View.GONE);
    reportSpamView.setBackgroundResource(kr.wdream.storyshop.R.drawable.blockpanel);
    contentView.addView(reportSpamView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));

    addToContactsButton = new TextView(context);
    addToContactsButton.setTextColor(Theme.CHAT_ADD_CONTACT_TEXT_COLOR);
    addToContactsButton.setVisibility(View.GONE);
    addToContactsButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    addToContactsButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    addToContactsButton.setSingleLine(true);
    addToContactsButton.setMaxLines(1);
    addToContactsButton.setPadding(AndroidUtilities.dp(4), 0, AndroidUtilities.dp(4), 0);
    addToContactsButton.setGravity(Gravity.CENTER);
    addToContactsButton
            .setText(LocaleController.getString("AddContactChat", kr.wdream.storyshop.R.string.AddContactChat));
    reportSpamView.addView(addToContactsButton, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, 0.5f, Gravity.LEFT | Gravity.TOP, 0, 0, 0, AndroidUtilities.dp(1)));
    addToContactsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Bundle args = new Bundle();
            args.putInt("user_id", currentUser.id);
            args.putBoolean("addContact", true);
            presentFragment(new ContactAddActivity(args));
        }
    });

    reportSpamContainer = new FrameLayout(context);
    reportSpamView.addView(reportSpamContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, 1.0f, Gravity.LEFT | Gravity.TOP, 0, 0, 0, AndroidUtilities.dp(1)));

    reportSpamButton = new TextView(context);
    reportSpamButton.setTextColor(Theme.CHAT_REPORT_SPAM_TEXT_COLOR);
    reportSpamButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    reportSpamButton.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    reportSpamButton.setSingleLine(true);
    reportSpamButton.setMaxLines(1);
    if (currentChat != null) {
        reportSpamButton.setText(LocaleController.getString("ReportSpamAndLeave",
                kr.wdream.storyshop.R.string.ReportSpamAndLeave));
    } else {
        reportSpamButton
                .setText(LocaleController.getString("ReportSpam", kr.wdream.storyshop.R.string.ReportSpam));
    }
    reportSpamButton.setGravity(Gravity.CENTER);
    reportSpamButton.setPadding(AndroidUtilities.dp(50), 0, AndroidUtilities.dp(50), 0);
    reportSpamContainer.addView(reportSpamButton, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP));
    reportSpamButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            if (ChatObject.isChannel(currentChat) && !currentChat.megagroup) {
                builder.setMessage(LocaleController.getString("ReportSpamAlertChannel",
                        kr.wdream.storyshop.R.string.ReportSpamAlertChannel));
            } else if (currentChat != null) {
                builder.setMessage(LocaleController.getString("ReportSpamAlertGroup",
                        kr.wdream.storyshop.R.string.ReportSpamAlertGroup));
            } else {
                builder.setMessage(LocaleController.getString("ReportSpamAlert",
                        kr.wdream.storyshop.R.string.ReportSpamAlert));
            }
            builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
            builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (currentUser != null) {
                                MessagesController.getInstance().blockUser(currentUser.id);
                            }
                            MessagesController.getInstance().reportSpam(dialog_id, currentUser, currentChat);
                            updateSpamView();
                            if (currentChat != null) {
                                if (ChatObject.isNotInChat(currentChat)) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                } else {
                                    MessagesController.getInstance().deleteUserFromChat((int) -dialog_id,
                                            MessagesController.getInstance()
                                                    .getUser(UserConfig.getClientUserId()),
                                            null);
                                }
                            } else {
                                MessagesController.getInstance().deleteDialog(dialog_id, 0);
                            }
                            finishFragment();
                        }
                    });
            builder.setNegativeButton(LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel),
                    null);
            showDialog(builder.create());
        }
    });

    ImageView closeReportSpam = new ImageView(context);
    closeReportSpam.setImageResource(kr.wdream.storyshop.R.drawable.miniplayer_close);
    closeReportSpam.setScaleType(ImageView.ScaleType.CENTER);
    reportSpamContainer.addView(closeReportSpam, LayoutHelper.createFrame(48, 48, Gravity.RIGHT | Gravity.TOP));
    closeReportSpam.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MessagesController.getInstance().hideReportSpam(dialog_id, currentUser, currentChat);
            updateSpamView();
        }
    });

    alertView = new FrameLayout(context);
    alertView.setTag(1);
    alertView.setTranslationY(-AndroidUtilities.dp(50));
    alertView.setVisibility(View.GONE);
    alertView.setBackgroundResource(kr.wdream.storyshop.R.drawable.blockpanel);
    contentView.addView(alertView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 50, Gravity.TOP | Gravity.LEFT));

    alertNameTextView = new TextView(context);
    alertNameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertNameTextView.setTextColor(Theme.ALERT_PANEL_NAME_TEXT_COLOR);
    alertNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    alertNameTextView.setSingleLine(true);
    alertNameTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertNameTextView.setMaxLines(1);
    alertView.addView(alertNameTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 5, 8, 0));

    alertTextView = new TextView(context);
    alertTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    alertTextView.setTextColor(Theme.ALERT_PANEL_MESSAGE_TEXT_COLOR);
    alertTextView.setSingleLine(true);
    alertTextView.setEllipsize(TextUtils.TruncateAt.END);
    alertTextView.setMaxLines(1);
    alertView.addView(alertTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.TOP | Gravity.LEFT, 8, 23, 8, 0));

    if (!isBroadcast) {
        mentionContainer = new FrameLayout(context) {

            private Drawable background;

            @Override
            public void onDraw(Canvas canvas) {
                if (mentionListView.getChildCount() <= 0) {
                    return;
                }
                if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()
                        && mentionsAdapter.getBotContextSwitch() == null) {
                    background.setBounds(0, mentionListViewScrollOffsetY - AndroidUtilities.dp(4),
                            getMeasuredWidth(), getMeasuredHeight());
                } else {
                    background.setBounds(0, mentionListViewScrollOffsetY - AndroidUtilities.dp(2),
                            getMeasuredWidth(), getMeasuredHeight());
                }
                background.draw(canvas);
            }

            @Override
            public void setBackgroundResource(int resid) {
                background = getContext().getResources().getDrawable(resid);
            }

            @Override
            public void requestLayout() {
                if (mentionListViewIgnoreLayout) {
                    return;
                }
                super.requestLayout();
            }
        };
        mentionContainer.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
        mentionContainer.setVisibility(View.GONE);
        mentionContainer.setWillNotDraw(false);
        contentView.addView(mentionContainer,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 110, Gravity.LEFT | Gravity.BOTTOM));

        mentionListView = new RecyclerListView(context) {

            private int lastWidth;
            private int lastHeight;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                if (!mentionListViewIsScrolling && mentionListViewScrollOffsetY != 0
                        && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        mentionListView, 0);
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public boolean onTouchEvent(MotionEvent event) {
                if (!mentionListViewIsScrolling && mentionListViewScrollOffsetY != 0
                        && event.getY() < mentionListViewScrollOffsetY) {
                    return false;
                }
                //supress warning
                return super.onTouchEvent(event);
            }

            @Override
            public void requestLayout() {
                if (mentionListViewIgnoreLayout) {
                    return;
                }
                super.requestLayout();
            }

            @Override
            protected void onLayout(boolean changed, int l, int t, int r, int b) {
                int width = r - l;
                int height = b - t;

                int newPosition = -1;
                int newTop = 0;
                if (mentionListView != null && mentionListViewLastViewPosition >= 0 && width == lastWidth
                        && height - lastHeight != 0) {
                    newPosition = mentionListViewLastViewPosition;
                    newTop = mentionListViewLastViewTop + height - lastHeight - getPaddingTop();
                }

                super.onLayout(changed, l, t, r, b);

                if (newPosition != -1) {
                    mentionListViewIgnoreLayout = true;
                    if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                        mentionGridLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                    } else {
                        mentionLayoutManager.scrollToPositionWithOffset(newPosition, newTop);
                    }
                    super.onLayout(false, l, t, r, b);
                    mentionListViewIgnoreLayout = false;
                }

                lastHeight = height;
                lastWidth = width;
                mentionListViewUpdateLayout();
            }
        };
        mentionListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, mentionListView, 0,
                        mentionsOnItemClickListener);
            }
        });
        mentionListView.setTag(2);
        mentionLayoutManager = new LinearLayoutManager(context) {
            @Override
            public boolean supportsPredictiveItemAnimations() {
                return false;
            }
        };
        mentionLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mentionGridLayoutManager = new ExtendedGridLayoutManager(context, 100) {

            private Size size = new Size();

            @Override
            protected Size getSizeForItem(int i) {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    i++;
                }
                Object object = mentionsAdapter.getItem(i);
                if (object instanceof TLRPC.BotInlineResult) {
                    TLRPC.BotInlineResult inlineResult = (TLRPC.BotInlineResult) object;
                    if (inlineResult.document != null) {
                        size.width = inlineResult.document.thumb != null ? inlineResult.document.thumb.w : 100;
                        size.height = inlineResult.document.thumb != null ? inlineResult.document.thumb.h : 100;
                        for (int b = 0; b < inlineResult.document.attributes.size(); b++) {
                            TLRPC.DocumentAttribute attribute = inlineResult.document.attributes.get(b);
                            if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                    || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                                size.width = attribute.w;
                                size.height = attribute.h;
                                break;
                            }
                        }
                    } else {
                        size.width = inlineResult.w;
                        size.height = inlineResult.h;
                    }
                }
                return size;
            }

            @Override
            protected int getFlowItemCount() {
                if (mentionsAdapter.getBotContextSwitch() != null) {
                    return getItemCount() - 1;
                }
                return super.getFlowItemCount();
            }
        };
        mentionGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                Object object = mentionsAdapter.getItem(position);
                if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                    return 100;
                } else {
                    if (mentionsAdapter.getBotContextSwitch() != null) {
                        position--;
                    }
                    return mentionGridLayoutManager.getSpanSizeForItem(position);
                }
            }
        });
        mentionListView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.left = 0;
                outRect.right = 0;
                outRect.top = 0;
                outRect.bottom = 0;
                if (parent.getLayoutManager() == mentionGridLayoutManager) {
                    int position = parent.getChildAdapterPosition(view);
                    if (mentionsAdapter.getBotContextSwitch() != null) {
                        if (position == 0) {
                            return;
                        }
                        position--;
                        if (!mentionGridLayoutManager.isFirstRow(position)) {
                            outRect.top = AndroidUtilities.dp(2);
                        }
                    } else {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = mentionGridLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            }
        });
        mentionListView.setItemAnimator(null);
        mentionListView.setLayoutAnimation(null);
        mentionListView.setClipToPadding(false);
        mentionListView.setLayoutManager(mentionLayoutManager);
        mentionListView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        mentionContainer.addView(mentionListView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

        mentionListView.setAdapter(mentionsAdapter = new MentionsAdapter(context, false, dialog_id,
                new MentionsAdapter.MentionsAdapterDelegate() {
                    @Override
                    public void needChangePanelVisibility(boolean show) {
                        if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                            mentionListView.setLayoutManager(mentionGridLayoutManager);
                        } else {
                            mentionListView.setLayoutManager(mentionLayoutManager);
                        }
                        if (show) {
                            if (mentionListAnimation != null) {
                                mentionListAnimation.cancel();
                                mentionListAnimation = null;
                            }

                            if (mentionContainer.getVisibility() == View.VISIBLE) {
                                mentionContainer.setAlpha(1.0f);
                                return;
                            }
                            if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                                mentionGridLayoutManager.scrollToPositionWithOffset(0, 10000);
                            } else {
                                mentionLayoutManager.scrollToPositionWithOffset(0, 10000);
                            }
                            if (allowStickersPanel && (!mentionsAdapter.isBotContext()
                                    || (allowContextBotPanel || allowContextBotPanelSecond))) {
                                if (currentEncryptedChat != null && mentionsAdapter.isBotContext()) {
                                    SharedPreferences preferences = ApplicationLoader.applicationContext
                                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                                    if (!preferences.getBoolean("secretbot", false)) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                                getParentActivity());
                                        builder.setTitle(LocaleController.getString("AppName",
                                                kr.wdream.storyshop.R.string.AppName));
                                        builder.setMessage(LocaleController.getString(
                                                "SecretChatContextBotAlert",
                                                kr.wdream.storyshop.R.string.SecretChatContextBotAlert));
                                        builder.setPositiveButton(LocaleController.getString("OK",
                                                kr.wdream.storyshop.R.string.OK), null);
                                        showDialog(builder.create());
                                        preferences.edit().putBoolean("secretbot", true).commit();
                                    }
                                }
                                mentionContainer.setVisibility(View.VISIBLE);
                                mentionContainer.setTag(null);
                                mentionListAnimation = new AnimatorSet();
                                mentionListAnimation.playTogether(
                                        ObjectAnimator.ofFloat(mentionContainer, "alpha", 0.0f, 1.0f));
                                mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }

                                    @Override
                                    public void onAnimationCancel(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }
                                });
                                mentionListAnimation.setDuration(200);
                                mentionListAnimation.start();
                            } else {
                                mentionContainer.setAlpha(1.0f);
                                mentionContainer.setVisibility(View.INVISIBLE);
                            }
                        } else {
                            if (mentionListAnimation != null) {
                                mentionListAnimation.cancel();
                                mentionListAnimation = null;
                            }

                            if (mentionContainer.getVisibility() == View.GONE) {
                                return;
                            }
                            if (allowStickersPanel) {
                                mentionListAnimation = new AnimatorSet();
                                mentionListAnimation
                                        .playTogether(ObjectAnimator.ofFloat(mentionContainer, "alpha", 0.0f));
                                mentionListAnimation.addListener(new AnimatorListenerAdapterProxy() {
                                    @Override
                                    public void onAnimationEnd(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionContainer.setVisibility(View.GONE);
                                            mentionContainer.setTag(null);
                                            mentionListAnimation = null;
                                        }
                                    }

                                    @Override
                                    public void onAnimationCancel(Animator animation) {
                                        if (mentionListAnimation != null
                                                && mentionListAnimation.equals(animation)) {
                                            mentionListAnimation = null;
                                        }
                                    }
                                });
                                mentionListAnimation.setDuration(200);
                                mentionListAnimation.start();
                            } else {
                                mentionContainer.setTag(null);
                                mentionContainer.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onContextSearch(boolean searching) {
                        if (chatActivityEnterView != null) {
                            chatActivityEnterView.setCaption(mentionsAdapter.getBotCaption());
                            chatActivityEnterView.showContextProgress(searching);
                        }
                    }

                    @Override
                    public void onContextClick(TLRPC.BotInlineResult result) {
                        if (getParentActivity() == null || result.content_url == null) {
                            return;
                        }
                        if (result.type.equals("video") || result.type.equals("web_player_video")) {
                            BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                            builder.setCustomView(new WebFrameLayout(getParentActivity(), builder.create(),
                                    result.title != null ? result.title : "", result.description,
                                    result.content_url, result.content_url, result.w, result.h));
                            builder.setUseFullWidth(true);
                            showDialog(builder.create());
                        } else {
                            Browser.openUrl(getParentActivity(), result.content_url);
                        }
                    }
                }));
        if (!ChatObject.isChannel(currentChat) || currentChat != null && currentChat.megagroup) {
            mentionsAdapter.setBotInfo(botInfo);
        }
        mentionsAdapter.setParentFragment(this);
        mentionsAdapter.setChatInfo(info);
        mentionsAdapter.setNeedUsernames(currentChat != null);
        mentionsAdapter.setNeedBotContext(currentEncryptedChat == null
                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
        mentionsAdapter.setBotsCount(currentChat != null ? botsCount : 1);
        mentionListView.setOnItemClickListener(
                mentionsOnItemClickListener = new RecyclerListView.OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Object object = mentionsAdapter.getItem(position);
                        int start = mentionsAdapter.getResultStartPosition();
                        int len = mentionsAdapter.getResultLength();
                        if (object instanceof TLRPC.User) {
                            TLRPC.User user = (TLRPC.User) object;
                            if (user != null) {
                                if (user.username != null) {
                                    chatActivityEnterView.replaceWithText(start, len,
                                            "@" + user.username + " ");
                                } else {
                                    String name = user.first_name;
                                    if (name == null || name.length() == 0) {
                                        name = user.last_name;
                                    }
                                    Spannable spannable = new SpannableString(name + " ");
                                    spannable.setSpan(new URLSpanUserMention("" + user.id), 0,
                                            spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                                    chatActivityEnterView.replaceWithText(start, len, spannable);
                                }
                            }
                        } else if (object instanceof String) {
                            if (mentionsAdapter.isBotCommands()) {
                                SendMessagesHelper.getInstance().sendMessage((String) object, dialog_id, null,
                                        null, false, null, null, null);
                                chatActivityEnterView.setFieldText("");
                            } else {
                                chatActivityEnterView.replaceWithText(start, len, object + " ");
                            }
                        } else if (object instanceof TLRPC.BotInlineResult) {
                            if (chatActivityEnterView.getFieldText() == null) {
                                return;
                            }
                            TLRPC.BotInlineResult result = (TLRPC.BotInlineResult) object;
                            if (Build.VERSION.SDK_INT >= 16 && (result.type.equals("photo")
                                    && (result.photo != null || result.content_url != null)
                                    || result.type.equals("gif")
                                            && (result.document != null || result.content_url != null)
                                    || result.type.equals("video")
                                            && (result.document != null/* || result.content_url != null*/))) {
                                ArrayList<Object> arrayList = botContextResults = new ArrayList<Object>(
                                        mentionsAdapter.getSearchResultBotContext());
                                PhotoViewer.getInstance().setParentActivity(getParentActivity());
                                PhotoViewer.getInstance().openPhotoForSelect(arrayList,
                                        mentionsAdapter.getItemPosition(position), 3, botContextProvider, null);
                            } else {
                                sendBotInlineResult(result);
                            }
                        } else if (object instanceof TLRPC.TL_inlineBotSwitchPM) {
                            processInlineBotContextPM((TLRPC.TL_inlineBotSwitchPM) object);
                        }
                    }
                });

        mentionListView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
            @Override
            public boolean onItemClick(View view, int position) {
                if (getParentActivity() == null || !mentionsAdapter.isLongClickEnabled()) {
                    return false;
                }
                Object object = mentionsAdapter.getItem(position);
                if (object instanceof String) {
                    if (mentionsAdapter.isBotCommands()) {
                        if (URLSpanBotCommand.enabled) {
                            chatActivityEnterView.setFieldText("");
                            chatActivityEnterView.setCommand(null, (String) object, true,
                                    currentChat != null && currentChat.megagroup);
                            return true;
                        }
                        return false;
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                        builder.setTitle(
                                LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                        builder.setMessage(LocaleController.getString("ClearSearch",
                                kr.wdream.storyshop.R.string.ClearSearch));
                        builder.setPositiveButton(LocaleController
                                .getString("ClearButton", kr.wdream.storyshop.R.string.ClearButton)
                                .toUpperCase(), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        mentionsAdapter.clearRecentHashtags();
                                    }
                                });
                        builder.setNegativeButton(
                                LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel),
                                null);
                        showDialog(builder.create());
                        return true;
                    }
                }
                return false;
            }
        });

        mentionListView.setOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                mentionListViewIsScrolling = newState == RecyclerView.SCROLL_STATE_DRAGGING;
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int lastVisibleItem;
                if (mentionsAdapter.isBotContext() && mentionsAdapter.isMediaLayout()) {
                    lastVisibleItem = mentionGridLayoutManager.findLastVisibleItemPosition();
                } else {
                    lastVisibleItem = mentionLayoutManager.findLastVisibleItemPosition();
                }
                int visibleItemCount = lastVisibleItem == RecyclerView.NO_POSITION ? 0 : lastVisibleItem;
                if (visibleItemCount > 0 && lastVisibleItem > mentionsAdapter.getItemCount() - 5) {
                    mentionsAdapter.searchForContextBotForNextOffset();
                }
                mentionListViewUpdateLayout();
            }
        });
    }

    pagedownButton = new FrameLayout(context);
    pagedownButton.setVisibility(View.INVISIBLE);
    contentView.addView(pagedownButton,
            LayoutHelper.createFrame(46, 59, Gravity.RIGHT | Gravity.BOTTOM, 0, 0, 7, 5));
    pagedownButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (returnToMessageId > 0) {
                scrollToMessageId(returnToMessageId, 0, true, returnToLoadIndex);
            } else {
                scrollToLastMessage(true);
            }
        }
    });

    ImageView pagedownButtonImage = new ImageView(context);
    pagedownButtonImage.setImageResource(kr.wdream.storyshop.R.drawable.pagedown);
    pagedownButton.addView(pagedownButtonImage,
            LayoutHelper.createFrame(46, 46, Gravity.LEFT | Gravity.BOTTOM));

    pagedownButtonCounter = new TextView(context);
    pagedownButtonCounter.setVisibility(View.INVISIBLE);
    pagedownButtonCounter.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    pagedownButtonCounter.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    pagedownButtonCounter.setTextColor(0xffffffff);
    pagedownButtonCounter.setGravity(Gravity.CENTER);
    pagedownButtonCounter.setBackgroundResource(kr.wdream.storyshop.R.drawable.chat_badge);
    pagedownButtonCounter.setMinWidth(AndroidUtilities.dp(23));
    pagedownButtonCounter.setPadding(AndroidUtilities.dp(8), 0, AndroidUtilities.dp(8), AndroidUtilities.dp(1));
    pagedownButton.addView(pagedownButtonCounter,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 23, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

    chatActivityEnterView = new ChatActivityEnterView(getParentActivity(), contentView, this, true);
    chatActivityEnterView.setDialogId(dialog_id);
    chatActivityEnterView.addToAttachLayout(menuItem);
    chatActivityEnterView.setId(id_chat_compose_panel);
    chatActivityEnterView.setBotsCount(botsCount, hasBotsCommands);
    chatActivityEnterView.setAllowStickersAndGifs(
            currentEncryptedChat == null
                    || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
            currentEncryptedChat == null
                    || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
    contentView.addView(chatActivityEnterView, contentView.getChildCount() - 1, LayoutHelper
            .createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.BOTTOM));
    chatActivityEnterView.setDelegate(new ChatActivityEnterView.ChatActivityEnterViewDelegate() {
        @Override
        public void onMessageSend(CharSequence message) {
            moveScrollToLastMessage();
            showReplyPanel(false, null, null, null, false, true);
            if (mentionsAdapter != null) {
                mentionsAdapter.addHashtagsFromMessage(message);
            }
        }

        @Override
        public void onTextChanged(final CharSequence text, boolean bigChange) {
            MediaController.getInstance().setInputFieldHasText(
                    text != null && text.length() != 0 || chatActivityEnterView.isEditingMessage());
            if (stickersAdapter != null && !chatActivityEnterView.isEditingMessage()) {
                stickersAdapter.loadStikersForEmoji(text);
            }
            if (mentionsAdapter != null) {
                mentionsAdapter.searchUsernameOrHashtag(text.toString(),
                        chatActivityEnterView.getCursorPosition(), messages);
            }
            if (waitingForCharaterEnterRunnable != null) {
                AndroidUtilities.cancelRunOnUIThread(waitingForCharaterEnterRunnable);
                waitingForCharaterEnterRunnable = null;
            }
            if (chatActivityEnterView.isMessageWebPageSearchEnabled()
                    && (!chatActivityEnterView.isEditingMessage()
                            || !chatActivityEnterView.isEditingCaption())) {
                if (bigChange) {
                    searchLinks(text, true);
                } else {
                    waitingForCharaterEnterRunnable = new Runnable() {
                        @Override
                        public void run() {
                            if (this == waitingForCharaterEnterRunnable) {
                                searchLinks(text, false);
                                waitingForCharaterEnterRunnable = null;
                            }
                        }
                    };
                    AndroidUtilities.runOnUIThread(waitingForCharaterEnterRunnable,
                            AndroidUtilities.WEB_URL == null ? 3000 : 1000);
                }
            }
        }

        @Override
        public void needSendTyping() {
            MessagesController.getInstance().sendTyping(dialog_id, 0, classGuid);
        }

        @Override
        public void onAttachButtonHidden() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.VISIBLE);
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.GONE);
            }
        }

        @Override
        public void onAttachButtonShow() {
            if (actionBar.isSearchFieldVisible()) {
                return;
            }
            if (attachItem != null) {
                attachItem.setVisibility(View.GONE);
            }
            if (headerItem != null) {
                headerItem.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onMessageEditEnd(boolean loading) {
            if (loading) {
                showEditDoneProgress(true, true);
            } else {
                mentionsAdapter.setNeedBotContext(currentEncryptedChat == null
                        || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
                chatListView.setOnItemLongClickListener(onItemLongClickListener);
                chatListView.setOnItemClickListener(onItemClickListener);
                chatListView.setClickable(true);
                chatListView.setLongClickable(true);
                mentionsAdapter.setAllowNewMentions(true);
                actionModeTitleContainer.setVisibility(View.GONE);
                selectedMessagesCountTextView.setVisibility(View.VISIBLE);
                chatActivityEnterView.setAllowStickersAndGifs(
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 23,
                        currentEncryptedChat == null
                                || AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46);
                if (editingMessageObjectReqId != 0) {
                    ConnectionsManager.getInstance().cancelRequest(editingMessageObjectReqId, true);
                    editingMessageObjectReqId = 0;
                }
                actionBar.hideActionMode();
                updatePinnedMessageView(true);
                updateVisibleRows();
            }
        }

        @Override
        public void onWindowSizeChanged(int size) {
            if (size < AndroidUtilities.dp(72) + ActionBar.getCurrentActionBarHeight()) {
                allowStickersPanel = false;
                if (stickersPanel.getVisibility() == View.VISIBLE) {
                    stickersPanel.setVisibility(View.INVISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.VISIBLE) {
                    mentionContainer.setVisibility(View.INVISIBLE);
                }
            } else {
                allowStickersPanel = true;
                if (stickersPanel.getVisibility() == View.INVISIBLE) {
                    stickersPanel.setVisibility(View.VISIBLE);
                }
                if (mentionContainer != null && mentionContainer.getVisibility() == View.INVISIBLE
                        && (!mentionsAdapter.isBotContext()
                                || (allowContextBotPanel || allowContextBotPanelSecond))) {
                    mentionContainer.setVisibility(View.VISIBLE);
                    mentionContainer.setTag(null);
                }
            }

            allowContextBotPanel = !chatActivityEnterView.isPopupShowing();
            checkContextBotPanel();
        }

        @Override
        public void onStickersTab(boolean opened) {
            if (emojiButtonRed != null) {
                emojiButtonRed.setVisibility(View.GONE);
            }
            allowContextBotPanelSecond = !opened;
            checkContextBotPanel();
        }
    });

    FrameLayout replyLayout = new FrameLayout(context) {
        @Override
        public void setTranslationY(float translationY) {
            super.setTranslationY(translationY);
            if (chatActivityEnterView != null) {
                chatActivityEnterView.invalidate();
            }
            if (getVisibility() != GONE) {
                int height = getLayoutParams().height;
                if (chatListView != null) {
                    chatListView.setTranslationY(translationY);
                }
                if (progressView != null) {
                    progressView.setTranslationY(translationY);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(translationY);
                }
                if (pagedownButton != null) {
                    pagedownButton.setTranslationY(translationY);
                }
            }
        }

        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }

        @Override
        public void setVisibility(int visibility) {
            super.setVisibility(visibility);
            if (visibility == GONE) {
                if (chatListView != null) {
                    chatListView.setTranslationY(0);
                }
                if (progressView != null) {
                    progressView.setTranslationY(0);
                }
                if (mentionContainer != null) {
                    mentionContainer.setTranslationY(0);
                }
                if (pagedownButton != null) {
                    pagedownButton
                            .setTranslationY(pagedownButton.getTag() == null ? AndroidUtilities.dp(100) : 0);
                }
            }
        }
    };
    replyLayout.setClickable(true);
    chatActivityEnterView.addTopView(replyLayout, 48);

    View lineView = new View(context);
    lineView.setBackgroundColor(0xffe8e8e8);
    replyLayout.addView(lineView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 1, Gravity.BOTTOM | Gravity.LEFT));

    replyIconImageView = new ImageView(context);
    replyIconImageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(replyIconImageView, LayoutHelper.createFrame(52, 46, Gravity.TOP | Gravity.LEFT));

    ImageView imageView = new ImageView(context);
    imageView.setImageResource(kr.wdream.storyshop.R.drawable.delete_reply);
    imageView.setScaleType(ImageView.ScaleType.CENTER);
    replyLayout.addView(imageView,
            LayoutHelper.createFrame(52, 46, Gravity.RIGHT | Gravity.TOP, 0, 0.5f, 0, 0));
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (forwardingMessages != null) {
                forwardingMessages.clear();
            }
            showReplyPanel(false, null, null, foundWebPage, true, true);
        }
    });

    replyNameTextView = new SimpleTextView(context);
    replyNameTextView.setTextSize(14);
    replyNameTextView.setTextColor(Theme.REPLY_PANEL_NAME_TEXT_COLOR);
    replyNameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    replyLayout.addView(replyNameTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 6, 52, 0));

    replyObjectTextView = new SimpleTextView(context);
    replyObjectTextView.setTextSize(14);
    replyObjectTextView.setTextColor(Theme.REPLY_PANEL_MESSAGE_TEXT_COLOR);
    replyLayout.addView(replyObjectTextView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 18, Gravity.TOP | Gravity.LEFT, 52, 24, 52, 0));

    replyImageView = new BackupImageView(context);
    replyLayout.addView(replyImageView,
            LayoutHelper.createFrame(34, 34, Gravity.TOP | Gravity.LEFT, 52, 6, 0, 0));

    stickersPanel = new FrameLayout(context);
    stickersPanel.setVisibility(View.GONE);
    contentView.addView(stickersPanel, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, 81.5f,
            Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 38));

    stickersListView = new RecyclerListView(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent event) {
            boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event, stickersListView,
                    0);
            return super.onInterceptTouchEvent(event) || result;
        }
    };
    stickersListView.setTag(3);
    stickersListView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return StickerPreviewViewer.getInstance().onTouch(event, stickersListView, 0,
                    stickersOnItemClickListener);
        }
    });
    stickersListView.setDisallowInterceptTouchEvents(true);
    LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    stickersListView.setLayoutManager(layoutManager);
    stickersListView.setClipToPadding(false);
    stickersListView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    stickersPanel.addView(stickersListView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 78));
    initStickers();

    imageView = new ImageView(context);
    imageView.setImageResource(kr.wdream.storyshop.R.drawable.stickers_back_arrow);
    stickersPanel.addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 53, 0, 0, 0));

    searchContainer = new FrameLayout(context);
    searchContainer.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
    searchContainer.setVisibility(View.INVISIBLE);
    searchContainer.setFocusable(true);
    searchContainer.setFocusableInTouchMode(true);
    searchContainer.setClickable(true);
    searchContainer.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
    searchContainer.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    contentView.addView(searchContainer,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));

    searchUpButton = new ImageView(context);
    searchUpButton.setScaleType(ImageView.ScaleType.CENTER);
    searchUpButton.setImageResource(kr.wdream.storyshop.R.drawable.search_up);
    searchContainer.addView(searchUpButton, LayoutHelper.createFrame(48, 48));
    searchUpButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 1);
        }
    });

    searchDownButton = new ImageView(context);
    searchDownButton.setScaleType(ImageView.ScaleType.CENTER);
    searchDownButton.setImageResource(kr.wdream.storyshop.R.drawable.search_down);
    searchContainer.addView(searchDownButton,
            LayoutHelper.createFrame(48, 48, Gravity.LEFT | Gravity.TOP, 48, 0, 0, 0));
    searchDownButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MessagesSearchQuery.searchMessagesInChat(null, dialog_id, mergeDialogId, classGuid, 2);
        }
    });

    searchCountText = new SimpleTextView(context);
    searchCountText.setTextColor(Theme.CHAT_SEARCH_COUNT_TEXT_COLOR);
    searchCountText.setTextSize(15);
    searchCountText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    searchContainer.addView(searchCountText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL, 108, 0, 0, 0));

    bottomOverlay = new FrameLayout(context);
    bottomOverlay.setVisibility(View.INVISIBLE);
    bottomOverlay.setFocusable(true);
    bottomOverlay.setFocusableInTouchMode(true);
    bottomOverlay.setClickable(true);
    bottomOverlay.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
    bottomOverlay.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    contentView.addView(bottomOverlay, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));

    bottomOverlayText = new TextView(context);
    bottomOverlayText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    bottomOverlayText.setTextColor(Theme.CHAT_BOTTOM_OVERLAY_TEXT_COLOR);
    bottomOverlay.addView(bottomOverlayText,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    bottomOverlayChat = new FrameLayout(context);
    bottomOverlayChat.setBackgroundResource(kr.wdream.storyshop.R.drawable.compose_panel);
    bottomOverlayChat.setPadding(0, AndroidUtilities.dp(3), 0, 0);
    bottomOverlayChat.setVisibility(View.INVISIBLE);
    contentView.addView(bottomOverlayChat,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 51, Gravity.BOTTOM));
    bottomOverlayChat.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = null;
            if (currentUser != null && userBlocked) {
                if (currentUser.bot) {
                    String botUserLast = botUser;
                    botUser = null;
                    MessagesController.getInstance().unblockUser(currentUser.id);
                    if (botUserLast != null && botUserLast.length() != 0) {
                        MessagesController.getInstance().sendBotStart(currentUser, botUserLast);
                    } else {
                        SendMessagesHelper.getInstance().sendMessage("/start", dialog_id, null, null, false,
                                null, null, null);
                    }
                } else {
                    builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("AreYouSureUnblockContact",
                            kr.wdream.storyshop.R.string.AreYouSureUnblockContact));
                    builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().unblockUser(currentUser.id);
                                }
                            });
                }
            } else if (currentUser != null && currentUser.bot && botUser != null) {
                if (botUser.length() != 0) {
                    MessagesController.getInstance().sendBotStart(currentUser, botUser);
                } else {
                    SendMessagesHelper.getInstance().sendMessage("/start", dialog_id, null, null, false, null,
                            null, null);
                }
                botUser = null;
                updateBottomOverlay();
            } else {
                if (ChatObject.isChannel(currentChat) && !(currentChat instanceof TLRPC.TL_channelForbidden)) {
                    if (ChatObject.isNotInChat(currentChat)) {
                        MessagesController.getInstance().addUserToChat(currentChat.id,
                                UserConfig.getCurrentUser(), null, 0, null, null);
                    } else {
                        toggleMute(true);
                    }
                } else {
                    builder = new AlertDialog.Builder(getParentActivity());
                    builder.setMessage(LocaleController.getString("AreYouSureDeleteThisChat",
                            kr.wdream.storyshop.R.string.AreYouSureDeleteThisChat));
                    builder.setPositiveButton(LocaleController.getString("OK", kr.wdream.storyshop.R.string.OK),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    MessagesController.getInstance().deleteDialog(dialog_id, 0);
                                    finishFragment();
                                }
                            });
                }
            }
            if (builder != null) {
                builder.setTitle(LocaleController.getString("AppName", kr.wdream.storyshop.R.string.AppName));
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showDialog(builder.create());
            }
        }
    });

    bottomOverlayChatText = new TextView(context);
    bottomOverlayChatText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
    bottomOverlayChatText.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    bottomOverlayChatText.setTextColor(Theme.CHAT_BOTTOM_CHAT_OVERLAY_TEXT_COLOR);
    bottomOverlayChat.addView(bottomOverlayChatText,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));

    chatAdapter.updateRows();
    if (loading && messages.isEmpty()) {
        progressView.setVisibility(chatAdapter.botInfoRow == -1 ? View.VISIBLE : View.INVISIBLE);
        chatListView.setEmptyView(null);
    } else {
        progressView.setVisibility(View.INVISIBLE);
        chatListView.setEmptyView(emptyViewContainer);
    }

    chatActivityEnterView.setButtons(userBlocked ? null : botButtons);

    if (!AndroidUtilities.isTablet() || AndroidUtilities.isSmallTablet()) {
        contentView.addView(playerView = new PlayerView(context, this), LayoutHelper
                .createFrame(LayoutHelper.MATCH_PARENT, 39, Gravity.TOP | Gravity.LEFT, 0, -36, 0, 0));
    }

    updateContactStatus();
    updateBottomOverlay();
    updateSecretStatus();
    updateSpamView();
    updatePinnedMessageView(true);

    try {
        if (currentEncryptedChat != null && Build.VERSION.SDK_INT >= 23) {
            getParentActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
                    WindowManager.LayoutParams.FLAG_SECURE);
        }
    } catch (Throwable e) {
        FileLog.e("tmessages", e);
    }
    fixLayoutInternal();

    contentView.addView(actionBar);

    return fragmentView;
}

From source file:com.nickandjerry.dynamiclayoutinflator.DynamicLayoutInflator.java

@SuppressLint("NewApi")
private static void applyAttributes(View view, Map<String, String> attrs, ViewGroup parent) {
    if (viewRunnables == null)
        createViewRunnables();/*from  w  w w  . ja va2 s . c  o  m*/
    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
    int layoutRule;
    int marginLeft = 0, marginRight = 0, marginTop = 0, marginBottom = 0, paddingLeft = 0, paddingRight = 0,
            paddingTop = 0, paddingBottom = 0;
    boolean hasCornerRadius = false, hasCornerRadii = false;
    for (Map.Entry<String, String> entry : attrs.entrySet()) {
        String attr = entry.getKey();
        if (viewRunnables.containsKey(attr)) {
            viewRunnables.get(attr).apply(view, entry.getValue(), parent, attrs);
            continue;
        }
        if (attr.startsWith("cornerRadius")) {
            hasCornerRadius = true;
            hasCornerRadii = !attr.equals("cornerRadius");
            continue;
        }
        layoutRule = NO_LAYOUT_RULE;
        boolean layoutTarget = false;
        switch (attr) {
        case "id":
            String idValue = parseId(entry.getValue());
            if (parent != null) {
                DynamicLayoutInfo info = getDynamicLayoutInfo(parent);
                int newId = highestIdNumberUsed++;
                view.setId(newId);
                info.nameToIdNumber.put(idValue, newId);
            }
            break;
        case "width":
        case "layout_width":
            switch (entry.getValue()) {
            case "wrap_content":
                layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
                break;
            case "fill_parent":
            case "match_parent":
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                break;
            default:
                layoutParams.width = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                        view.getResources().getDisplayMetrics(), parent, true);
                break;
            }
            break;
        case "height":
        case "layout_height":
            switch (entry.getValue()) {
            case "wrap_content":
                layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                break;
            case "fill_parent":
            case "match_parent":
                layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                break;
            default:
                layoutParams.height = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                        view.getResources().getDisplayMetrics(), parent, false);
                break;
            }
            break;
        case "layout_gravity":
            if (parent != null && parent instanceof LinearLayout) {
                ((LinearLayout.LayoutParams) layoutParams).gravity = parseGravity(entry.getValue());
            } else if (parent != null && parent instanceof FrameLayout) {
                ((FrameLayout.LayoutParams) layoutParams).gravity = parseGravity(entry.getValue());
            }
            break;
        case "layout_weight":
            if (parent != null && parent instanceof LinearLayout) {
                ((LinearLayout.LayoutParams) layoutParams).weight = Float.parseFloat(entry.getValue());
            }
            break;
        case "layout_below":
            layoutRule = RelativeLayout.BELOW;
            layoutTarget = true;
            break;
        case "layout_above":
            layoutRule = RelativeLayout.ABOVE;
            layoutTarget = true;
            break;
        case "layout_toLeftOf":
            layoutRule = RelativeLayout.LEFT_OF;
            layoutTarget = true;
            break;
        case "layout_toRightOf":
            layoutRule = RelativeLayout.RIGHT_OF;
            layoutTarget = true;
            break;
        case "layout_alignBottom":
            layoutRule = RelativeLayout.ALIGN_BOTTOM;
            layoutTarget = true;
            break;
        case "layout_alignTop":
            layoutRule = RelativeLayout.ALIGN_TOP;
            layoutTarget = true;
            break;
        case "layout_alignLeft":
        case "layout_alignStart":
            layoutRule = RelativeLayout.ALIGN_LEFT;
            layoutTarget = true;
            break;
        case "layout_alignRight":
        case "layout_alignEnd":
            layoutRule = RelativeLayout.ALIGN_RIGHT;
            layoutTarget = true;
            break;
        case "layout_alignParentBottom":
            layoutRule = RelativeLayout.ALIGN_PARENT_BOTTOM;
            break;
        case "layout_alignParentTop":
            layoutRule = RelativeLayout.ALIGN_PARENT_TOP;
            break;
        case "layout_alignParentLeft":
        case "layout_alignParentStart":
            layoutRule = RelativeLayout.ALIGN_PARENT_LEFT;
            break;
        case "layout_alignParentRight":
        case "layout_alignParentEnd":
            layoutRule = RelativeLayout.ALIGN_PARENT_RIGHT;
            break;
        case "layout_centerHorizontal":
            layoutRule = RelativeLayout.CENTER_HORIZONTAL;
            break;
        case "layout_centerVertical":
            layoutRule = RelativeLayout.CENTER_VERTICAL;
            break;
        case "layout_centerInParent":
            layoutRule = RelativeLayout.CENTER_IN_PARENT;
            break;
        case "layout_margin":
            marginLeft = marginRight = marginTop = marginBottom = DimensionConverter
                    .stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics());
            break;
        case "layout_marginLeft":
            marginLeft = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics(), parent, true);
            break;
        case "layout_marginTop":
            marginTop = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics(), parent, false);
            break;
        case "layout_marginRight":
            marginRight = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics(), parent, true);
            break;
        case "layout_marginBottom":
            marginBottom = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics(), parent, false);
            break;
        case "padding":
            paddingBottom = paddingLeft = paddingRight = paddingTop = DimensionConverter
                    .stringToDimensionPixelSize(entry.getValue(), view.getResources().getDisplayMetrics());
            break;
        case "paddingLeft":
            paddingLeft = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics());
            break;
        case "paddingTop":
            paddingTop = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics());
            break;
        case "paddingRight":
            paddingRight = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics());
            break;
        case "paddingBottom":
            paddingBottom = DimensionConverter.stringToDimensionPixelSize(entry.getValue(),
                    view.getResources().getDisplayMetrics());
            break;

        }
        if (layoutRule != NO_LAYOUT_RULE && parent instanceof RelativeLayout) {
            if (layoutTarget) {
                int anchor = idNumFromIdString(parent, parseId(entry.getValue()));
                ((RelativeLayout.LayoutParams) layoutParams).addRule(layoutRule, anchor);
            } else if (entry.getValue().equals("true")) {
                ((RelativeLayout.LayoutParams) layoutParams).addRule(layoutRule);
            }
        }
    }
    // TODO: this is a giant mess; come up with a simpler way of deciding what to draw for the background
    if (attrs.containsKey("background") || attrs.containsKey("borderColor")) {
        String bgValue = attrs.containsKey("background") ? attrs.get("background") : null;
        if (bgValue != null && bgValue.startsWith("@drawable/")) {
            view.setBackground(getDrawableByName(view, bgValue));
        } else if (bgValue == null || bgValue.startsWith("#") || bgValue.startsWith("@color")) {
            if (view instanceof Button || attrs.containsKey("pressedColor")) {
                int bgColor = parseColor(view, bgValue == null ? "#00000000" : bgValue);
                int pressedColor;
                if (attrs.containsKey("pressedColor")) {
                    pressedColor = parseColor(view, attrs.get("pressedColor"));
                } else {
                    pressedColor = adjustBrightness(bgColor, 0.9f);
                }
                GradientDrawable gd = new GradientDrawable();
                gd.setColor(bgColor);
                GradientDrawable pressedGd = new GradientDrawable();
                pressedGd.setColor(pressedColor);
                if (hasCornerRadii) {
                    float radii[] = new float[8];
                    for (int i = 0; i < CORNERS.length; i++) {
                        String corner = CORNERS[i];
                        if (attrs.containsKey("cornerRadius" + corner)) {
                            radii[i * 2] = radii[i * 2 + 1] = DimensionConverter.stringToDimension(
                                    attrs.get("cornerRadius" + corner),
                                    view.getResources().getDisplayMetrics());
                        }
                        gd.setCornerRadii(radii);
                        pressedGd.setCornerRadii(radii);
                    }
                } else if (hasCornerRadius) {
                    float cornerRadius = DimensionConverter.stringToDimension(attrs.get("cornerRadius"),
                            view.getResources().getDisplayMetrics());
                    gd.setCornerRadius(cornerRadius);
                    pressedGd.setCornerRadius(cornerRadius);
                }
                if (attrs.containsKey("borderColor")) {
                    String borderWidth = "1dp";
                    if (attrs.containsKey("borderWidth")) {
                        borderWidth = attrs.get("borderWidth");
                    }
                    int borderWidthPx = DimensionConverter.stringToDimensionPixelSize(borderWidth,
                            view.getResources().getDisplayMetrics());
                    gd.setStroke(borderWidthPx, parseColor(view, attrs.get("borderColor")));
                    pressedGd.setStroke(borderWidthPx, parseColor(view, attrs.get("borderColor")));
                }
                StateListDrawable selector = new StateListDrawable();
                selector.addState(new int[] { android.R.attr.state_pressed }, pressedGd);
                selector.addState(new int[] {}, gd);
                view.setBackground(selector);
                getDynamicLayoutInfo(view).bgDrawable = gd;
            } else if (hasCornerRadius || attrs.containsKey("borderColor")) {
                GradientDrawable gd = new GradientDrawable();
                int bgColor = parseColor(view, bgValue == null ? "#00000000" : bgValue);
                gd.setColor(bgColor);
                if (hasCornerRadii) {
                    float radii[] = new float[8];
                    for (int i = 0; i < CORNERS.length; i++) {
                        String corner = CORNERS[i];
                        if (attrs.containsKey("cornerRadius" + corner)) {
                            radii[i * 2] = radii[i * 2 + 1] = DimensionConverter.stringToDimension(
                                    attrs.get("cornerRadius" + corner),
                                    view.getResources().getDisplayMetrics());
                        }
                        gd.setCornerRadii(radii);
                    }
                } else if (hasCornerRadius) {
                    float cornerRadius = DimensionConverter.stringToDimension(attrs.get("cornerRadius"),
                            view.getResources().getDisplayMetrics());
                    gd.setCornerRadius(cornerRadius);
                }
                if (attrs.containsKey("borderColor")) {
                    String borderWidth = "1dp";
                    if (attrs.containsKey("borderWidth")) {
                        borderWidth = attrs.get("borderWidth");
                    }
                    gd.setStroke(
                            DimensionConverter.stringToDimensionPixelSize(borderWidth,
                                    view.getResources().getDisplayMetrics()),
                            parseColor(view, attrs.get("borderColor")));
                }
                view.setBackground(gd);
                getDynamicLayoutInfo(view).bgDrawable = gd;
            } else {
                view.setBackgroundColor(parseColor(view, bgValue));
            }
        }
    }

    if (layoutParams instanceof ViewGroup.MarginLayoutParams) {
        ((ViewGroup.MarginLayoutParams) layoutParams).setMargins(marginLeft, marginTop, marginRight,
                marginBottom);
    }
    view.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
    view.setLayoutParams(layoutParams);
}