Example usage for android.widget FrameLayout FrameLayout

List of usage examples for android.widget FrameLayout FrameLayout

Introduction

In this page you can find the example usage for android.widget FrameLayout FrameLayout.

Prototype

public FrameLayout(@NonNull Context context) 

Source Link

Usage

From source file:org.telegram.ui.ThemeActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(false);
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }//  ww w .  j  a  v  a2 s  .  c om
    if (currentType == THEME_TYPE_BASIC) {
        actionBar.setTitle(LocaleController.getString("ChatSettings", R.string.ChatSettings));
        ActionBarMenu menu = actionBar.createMenu();
        ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
        item.addSubItem(create_theme,
                LocaleController.getString("CreateNewThemeMenu", R.string.CreateNewThemeMenu));
    } else {
        actionBar.setTitle(LocaleController.getString("AutoNightTheme", R.string.AutoNightTheme));
    }

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == create_theme) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("NewTheme", R.string.NewTheme));
                builder.setMessage(
                        LocaleController.getString("CreateNewThemeAlert", R.string.CreateNewThemeAlert));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                builder.setPositiveButton(LocaleController.getString("CreateTheme", R.string.CreateTheme),
                        (dialog, which) -> openThemeCreate());
                showDialog(builder.create());
            }
        }
    });

    listAdapter = new ListAdapter(context);

    FrameLayout frameLayout = new FrameLayout(context);
    frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    fragmentView = frameLayout;

    listView = new RecyclerListView(context);
    listView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
    listView.setVerticalScrollBarEnabled(false);
    listView.setAdapter(listAdapter);
    ((DefaultItemAnimator) listView.getItemAnimator()).setDelayAnimations(false);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setOnItemClickListener((view, position) -> {
        if (position == enableAnimationsRow) {
            SharedPreferences preferences = MessagesController.getGlobalMainSettings();
            boolean animations = preferences.getBoolean("view_animations", true);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("view_animations", !animations);
            editor.commit();
            if (view instanceof TextCheckCell) {
                ((TextCheckCell) view).setChecked(!animations);
            }
        } else if (position == backgroundRow) {
            presentFragment(new WallpapersListActivity(WallpapersListActivity.TYPE_ALL));
        } else if (position == sendByEnterRow) {
            SharedPreferences preferences = MessagesController.getGlobalMainSettings();
            boolean send = preferences.getBoolean("send_by_enter", false);
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("send_by_enter", !send);
            editor.commit();
            if (view instanceof TextCheckCell) {
                ((TextCheckCell) view).setChecked(!send);
            }
        } else if (position == raiseToSpeakRow) {
            SharedConfig.toogleRaiseToSpeak();
            if (view instanceof TextCheckCell) {
                ((TextCheckCell) view).setChecked(SharedConfig.raiseToSpeak);
            }
        } else if (position == saveToGalleryRow) {
            SharedConfig.toggleSaveToGallery();
            if (view instanceof TextCheckCell) {
                ((TextCheckCell) view).setChecked(SharedConfig.saveToGallery);
            }
        } else if (position == customTabsRow) {
            SharedConfig.toggleCustomTabs();
            if (view instanceof TextCheckCell) {
                ((TextCheckCell) view).setChecked(SharedConfig.customTabs);
            }
        } else if (position == directShareRow) {
            SharedConfig.toggleDirectShare();
            if (view instanceof TextCheckCell) {
                ((TextCheckCell) view).setChecked(SharedConfig.directShare);
            }
        } else if (position == contactsReimportRow) {
            //not implemented
        } else if (position == contactsSortRow) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("SortBy", R.string.SortBy));
            builder.setItems(
                    new CharSequence[] { LocaleController.getString("Default", R.string.Default),
                            LocaleController.getString("SortFirstName", R.string.SortFirstName),
                            LocaleController.getString("SortLastName", R.string.SortLastName) },
                    (dialog, which) -> {
                        SharedPreferences preferences = MessagesController.getGlobalMainSettings();
                        SharedPreferences.Editor editor = preferences.edit();
                        editor.putInt("sortContactsBy", which);
                        editor.commit();
                        if (listAdapter != null) {
                            listAdapter.notifyItemChanged(position);
                        }
                    });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            showDialog(builder.create());
        } else if (position == stickersRow) {
            presentFragment(new StickersActivity(DataQuery.TYPE_IMAGE));
        } else if (position == emojiRow) {
            if (getParentActivity() == null) {
                return;
            }
            final boolean maskValues[] = new boolean[2];
            BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());

            builder.setApplyTopPadding(false);
            builder.setApplyBottomPadding(false);
            LinearLayout linearLayout = new LinearLayout(getParentActivity());
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            for (int a = 0; a < (Build.VERSION.SDK_INT >= 19 ? 2 : 1); a++) {
                String name = null;
                if (a == 0) {
                    maskValues[a] = SharedConfig.allowBigEmoji;
                    name = LocaleController.getString("EmojiBigSize", R.string.EmojiBigSize);
                } else if (a == 1) {
                    maskValues[a] = SharedConfig.useSystemEmoji;
                    name = LocaleController.getString("EmojiUseDefault", R.string.EmojiUseDefault);
                }
                CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity(), 1, 21);
                checkBoxCell.setTag(a);
                checkBoxCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
                linearLayout.addView(checkBoxCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50));
                checkBoxCell.setText(name, "", maskValues[a], true);
                checkBoxCell.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));
                checkBoxCell.setOnClickListener(v -> {
                    CheckBoxCell cell = (CheckBoxCell) v;
                    int num = (Integer) cell.getTag();
                    maskValues[num] = !maskValues[num];
                    cell.setChecked(maskValues[num], true);
                });
            }
            BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1);
            cell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
            cell.setTextAndIcon(LocaleController.getString("Save", R.string.Save).toUpperCase(), 0);
            cell.setTextColor(Theme.getColor(Theme.key_dialogTextBlue2));
            cell.setOnClickListener(v -> {
                try {
                    if (visibleDialog != null) {
                        visibleDialog.dismiss();
                    }
                } catch (Exception e) {
                    FileLog.e(e);
                }
                SharedPreferences.Editor editor = MessagesController.getGlobalMainSettings().edit();
                editor.putBoolean("allowBigEmoji", SharedConfig.allowBigEmoji = maskValues[0]);
                editor.putBoolean("useSystemEmoji", SharedConfig.useSystemEmoji = maskValues[1]);
                editor.commit();
                if (listAdapter != null) {
                    listAdapter.notifyItemChanged(position);
                }
            });
            linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 50));
            builder.setCustomView(linearLayout);
            showDialog(builder.create());
        } else if (position >= themeStartRow && position < themeEndRow) {
            int p = position - themeStartRow;
            if (p >= 0 && p < Theme.themes.size()) {
                Theme.ThemeInfo themeInfo = Theme.themes.get(p);
                if (currentType == THEME_TYPE_BASIC) {
                    if (themeInfo == Theme.getCurrentTheme()) {
                        return;
                    }
                    NotificationCenter.getGlobalInstance()
                            .postNotificationName(NotificationCenter.needSetDayNightTheme, themeInfo, false);
                } else {
                    Theme.setCurrentNightTheme(themeInfo);
                }
                int count = listView.getChildCount();
                for (int a = 0; a < count; a++) {
                    View child = listView.getChildAt(a);
                    if (child instanceof ThemeCell) {
                        ((ThemeCell) child).updateCurrentThemeCheck();
                    }
                }
            }
        } else if (position == nightThemeRow) {
            presentFragment(new ThemeActivity(THEME_TYPE_NIGHT));
        } else if (position == nightDisabledRow) {
            Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_NONE;
            updateRows();
            Theme.checkAutoNightThemeConditions();
        } else if (position == nightScheduledRow) {
            Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_SCHEDULED;
            if (Theme.autoNightScheduleByLocation) {
                updateSunTime(null, true);
            }
            updateRows();
            Theme.checkAutoNightThemeConditions();
        } else if (position == nightAutomaticRow) {
            Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_AUTOMATIC;
            updateRows();
            Theme.checkAutoNightThemeConditions();
        } else if (position == scheduleLocationRow) {
            Theme.autoNightScheduleByLocation = !Theme.autoNightScheduleByLocation;
            TextCheckCell checkCell = (TextCheckCell) view;
            checkCell.setChecked(Theme.autoNightScheduleByLocation);
            updateRows();
            if (Theme.autoNightScheduleByLocation) {
                updateSunTime(null, true);
            }
            Theme.checkAutoNightThemeConditions();
        } else if (position == scheduleFromRow || position == scheduleToRow) {
            if (getParentActivity() == null) {
                return;
            }
            int currentHour;
            int currentMinute;
            if (position == scheduleFromRow) {
                currentHour = Theme.autoNightDayStartTime / 60;
                currentMinute = (Theme.autoNightDayStartTime - currentHour * 60);
            } else {
                currentHour = Theme.autoNightDayEndTime / 60;
                currentMinute = (Theme.autoNightDayEndTime - currentHour * 60);
            }
            final TextSettingsCell cell = (TextSettingsCell) view;
            TimePickerDialog dialog = new TimePickerDialog(getParentActivity(), (view1, hourOfDay, minute) -> {
                int time = hourOfDay * 60 + minute;
                if (position == scheduleFromRow) {
                    Theme.autoNightDayStartTime = time;
                    cell.setTextAndValue(LocaleController.getString("AutoNightFrom", R.string.AutoNightFrom),
                            String.format("%02d:%02d", hourOfDay, minute), true);
                } else {
                    Theme.autoNightDayEndTime = time;
                    cell.setTextAndValue(LocaleController.getString("AutoNightTo", R.string.AutoNightTo),
                            String.format("%02d:%02d", hourOfDay, minute), true);
                }
            }, currentHour, currentMinute, true);
            showDialog(dialog);
        } else if (position == scheduleUpdateLocationRow) {
            updateSunTime(null, true);
        }
    });

    return fragmentView;
}

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

@Override
public View createView(Context context) {
    actionBar.setBackButtonDrawable(new BackDrawable(false));
    actionBar.setTitle("");
    actionBar.setAllowOverlayTitle(false);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override// w  w w  .  j av  a 2s  .  c o  m
        public void onItemClick(int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    for (int a = 1; a >= 0; a--) {
                        selectedFiles[a].clear();
                    }
                    cantDeleteMessagesCount = 0;
                    actionBar.hideActionMode();
                    listView.invalidateViews();
                } else {
                    finishFragment();
                }
            } else if (id == shared_media_item) {
                if (selectedMode == 0) {
                    return;
                }
                selectedMode = 0;
                switchToCurrentSelectedMode();
            } else if (id == files_item) {
                if (selectedMode == 1) {
                    return;
                }
                selectedMode = 1;
                switchToCurrentSelectedMode();
            } else if (id == links_item) {
                if (selectedMode == 3) {
                    return;
                }
                selectedMode = 3;
                switchToCurrentSelectedMode();
            } else if (id == music_item) {
                if (selectedMode == 4) {
                    return;
                }
                selectedMode = 4;
                switchToCurrentSelectedMode();
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(LocaleController.formatString("AreYouSureDeleteMessages",
                        R.string.AreYouSureDeleteMessages, LocaleController.formatPluralString("items",
                                selectedFiles[0].size() + selectedFiles[1].size())));
                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) {
                                for (int a = 1; a >= 0; a--) {
                                    ArrayList<Integer> ids = new ArrayList<>(selectedFiles[a].keySet());
                                    ArrayList<Long> random_ids = null;
                                    TLRPC.EncryptedChat currentEncryptedChat = null;
                                    int channelId = 0;
                                    if (!ids.isEmpty()) {
                                        MessageObject msg = selectedFiles[a].get(ids.get(0));
                                        if (channelId == 0 && msg.messageOwner.to_id.channel_id != 0) {
                                            channelId = msg.messageOwner.to_id.channel_id;
                                        }
                                    }
                                    if ((int) dialog_id == 0) {
                                        currentEncryptedChat = MessagesController.getInstance()
                                                .getEncryptedChat((int) (dialog_id >> 32));
                                    }
                                    if (currentEncryptedChat != null) {
                                        random_ids = new ArrayList<>();
                                        for (HashMap.Entry<Integer, MessageObject> entry : selectedFiles[a]
                                                .entrySet()) {
                                            MessageObject msg = entry.getValue();
                                            if (msg.messageOwner.random_id != 0 && msg.type != 10) {
                                                random_ids.add(msg.messageOwner.random_id);
                                            }
                                        }
                                    }
                                    MessagesController.getInstance().deleteMessages(ids, random_ids,
                                            currentEncryptedChat, channelId);
                                    selectedFiles[a].clear();
                                }
                                actionBar.hideActionMode();
                                actionBar.closeSearchField();
                                cantDeleteMessagesCount = 0;
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == forward) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() {
                    @Override
                    public void didSelectDialog(DialogsActivity fragment, long did, boolean param) {
                        int lower_part = (int) did;
                        if (lower_part != 0) {
                            Bundle args = new Bundle();
                            args.putBoolean("scrollToTopOnResume", true);
                            if (lower_part > 0) {
                                args.putInt("user_id", lower_part);
                            } else if (lower_part < 0) {
                                args.putInt("chat_id", -lower_part);
                            }
                            if (!MessagesController.checkCanOpenChat(args, fragment)) {
                                return;
                            }

                            ArrayList<MessageObject> fmessages = new ArrayList<>();
                            for (int a = 1; a >= 0; a--) {
                                ArrayList<Integer> ids = new ArrayList<>(selectedFiles[a].keySet());
                                Collections.sort(ids);
                                for (Integer id : ids) {
                                    if (id > 0) {
                                        fmessages.add(selectedFiles[a].get(id));
                                    }
                                }
                                selectedFiles[a].clear();
                            }
                            cantDeleteMessagesCount = 0;
                            actionBar.hideActionMode();

                            NotificationCenter.getInstance()
                                    .postNotificationName(NotificationCenter.closeChats);

                            ChatActivity chatActivity = new ChatActivity(args);
                            presentFragment(chatActivity, true);
                            chatActivity.showReplyPanel(true, null, fmessages, null, false, false);

                            if (!AndroidUtilities.isTablet()) {
                                removeSelfFromStack();
                            }
                        } else {
                            fragment.finishFragment();
                        }
                    }
                });
                presentFragment(fragment);
            }
        }
    });

    for (int a = 1; a >= 0; a--) {
        selectedFiles[a].clear();
    }
    cantDeleteMessagesCount = 0;
    actionModeViews.clear();

    final ActionBarMenu menu = actionBar.createMenu();
    searchItem = menu.addItem(0, R.drawable.ic_ab_search).setIsSearchField(true)
            .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
                @Override
                public void onSearchExpand() {
                    dropDownContainer.setVisibility(View.GONE);
                    searching = true;
                }

                @Override
                public void onSearchCollapse() {
                    dropDownContainer.setVisibility(View.VISIBLE);
                    if (selectedMode == 1) {
                        documentsSearchAdapter.search(null);
                    } else if (selectedMode == 3) {
                        linksSearchAdapter.search(null);
                    } else if (selectedMode == 4) {
                        audioSearchAdapter.search(null);
                    }
                    searching = false;
                    searchWas = false;
                    switchToCurrentSelectedMode();
                }

                @Override
                public void onTextChanged(EditText editText) {
                    String text = editText.getText().toString();
                    if (text.length() != 0) {
                        searchWas = true;
                        switchToCurrentSelectedMode();
                    }
                    if (selectedMode == 1) {
                        if (documentsSearchAdapter == null) {
                            return;
                        }
                        documentsSearchAdapter.search(text);
                    } else if (selectedMode == 3) {
                        if (linksSearchAdapter == null) {
                            return;
                        }
                        linksSearchAdapter.search(text);
                    } else if (selectedMode == 4) {
                        if (audioSearchAdapter == null) {
                            return;
                        }
                        audioSearchAdapter.search(text);
                    }
                }
            });
    searchItem.getSearchField().setHint(LocaleController.getString("Search", R.string.Search));
    searchItem.setVisibility(View.GONE);

    dropDownContainer = new ActionBarMenuItem(context, menu, 0);
    dropDownContainer.setSubMenuOpenSide(1);
    dropDownContainer.addSubItem(shared_media_item,
            LocaleController.getString("SharedMediaTitle", R.string.SharedMediaTitle), 0);
    dropDownContainer.addSubItem(files_item,
            LocaleController.getString("DocumentsTitle", R.string.DocumentsTitle), 0);
    if ((int) dialog_id != 0) {
        dropDownContainer.addSubItem(links_item, LocaleController.getString("LinksTitle", R.string.LinksTitle),
                0);
        dropDownContainer.addSubItem(music_item, LocaleController.getString("AudioTitle", R.string.AudioTitle),
                0);
    } else {
        TLRPC.EncryptedChat currentEncryptedChat = MessagesController.getInstance()
                .getEncryptedChat((int) (dialog_id >> 32));
        if (currentEncryptedChat != null
                && AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46) {
            dropDownContainer.addSubItem(music_item,
                    LocaleController.getString("AudioTitle", R.string.AudioTitle), 0);
        }
    }
    actionBar.addView(dropDownContainer, 0,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT,
                    Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 64 : 56, 0, 40, 0));
    dropDownContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dropDownContainer.toggleSubMenu();
        }
    });

    dropDown = new TextView(context);
    dropDown.setGravity(Gravity.LEFT);
    dropDown.setSingleLine(true);
    dropDown.setLines(1);
    dropDown.setMaxLines(1);
    dropDown.setEllipsize(TextUtils.TruncateAt.END);
    dropDown.setTextColor(0xffffffff);
    dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_arrow_drop_down, 0);
    dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4));
    dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0);
    dropDownContainer.addView(dropDown, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 16, 0, 0, 0));

    final ActionBarMenu actionMode = actionBar.createActionMode();

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

    if ((int) dialog_id != 0) {
        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)));

    photoVideoAdapter = new SharedPhotoVideoAdapter(context);
    documentsAdapter = new SharedDocumentsAdapter(context, 1);
    audioAdapter = new SharedDocumentsAdapter(context, 4);
    documentsSearchAdapter = new MediaSearchAdapter(context, 1);
    audioSearchAdapter = new MediaSearchAdapter(context, 4);
    linksSearchAdapter = new MediaSearchAdapter(context, 3);
    linksAdapter = new SharedLinksAdapter(context);

    FrameLayout frameLayout;
    fragmentView = frameLayout = new FrameLayout(context);

    listView = new SectionsListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setDrawSelectorOnTop(true);
    listView.setClipToPadding(false);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
            if ((selectedMode == 1 || selectedMode == 4) && view instanceof SharedDocumentCell) {
                MediaActivity.this.onItemClick(i, view, ((SharedDocumentCell) view).getMessage(), 0);
            } else if (selectedMode == 3 && view instanceof SharedLinkCell) {
                MediaActivity.this.onItemClick(i, view, ((SharedLinkCell) view).getMessage(), 0);
            }
        }
    });
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
                AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
            }
            scrolling = scrollState != SCROLL_STATE_IDLE;
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (searching && searchWas) {
                return;
            }
            if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2
                    && !sharedMediaData[selectedMode].loading) {
                int type;
                if (selectedMode == 0) {
                    type = SharedMediaQuery.MEDIA_PHOTOVIDEO;
                } else if (selectedMode == 1) {
                    type = SharedMediaQuery.MEDIA_FILE;
                } else if (selectedMode == 2) {
                    type = SharedMediaQuery.MEDIA_AUDIO;
                } else if (selectedMode == 4) {
                    type = SharedMediaQuery.MEDIA_MUSIC;
                } else {
                    type = SharedMediaQuery.MEDIA_URL;
                }
                if (!sharedMediaData[selectedMode].endReached[0]) {
                    sharedMediaData[selectedMode].loading = true;
                    SharedMediaQuery.loadMedia(dialog_id, 0, 50, sharedMediaData[selectedMode].max_id[0], type,
                            true, classGuid);
                } else if (mergeDialogId != 0 && !sharedMediaData[selectedMode].endReached[1]) {
                    sharedMediaData[selectedMode].loading = true;
                    SharedMediaQuery.loadMedia(mergeDialogId, 0, 50, sharedMediaData[selectedMode].max_id[1],
                            type, true, classGuid);
                }
            }
        }
    });
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long id) {
            if ((selectedMode == 1 || selectedMode == 4) && view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                MessageObject message = cell.getMessage();
                return MediaActivity.this.onItemLongClick(message, view, 0);
            } else if (selectedMode == 3 && view instanceof SharedLinkCell) {
                SharedLinkCell cell = (SharedLinkCell) view;
                MessageObject message = cell.getMessage();
                return MediaActivity.this.onItemLongClick(message, view, 0);
            }
            return false;
        }
    });

    for (int a = 0; a < 6; a++) {
        cellCache.add(new SharedPhotoVideoCell(context));
    }

    emptyView = new LinearLayout(context);
    emptyView.setOrientation(LinearLayout.VERTICAL);
    emptyView.setGravity(Gravity.CENTER);
    emptyView.setVisibility(View.GONE);
    emptyView.setBackgroundColor(0xfff0f0f0);
    frameLayout.addView(emptyView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    emptyView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    emptyImageView = new ImageView(context);
    emptyView.addView(emptyImageView,
            LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));

    emptyTextView = new TextView(context);
    emptyTextView.setTextColor(0xff8a8a8a);
    emptyTextView.setGravity(Gravity.CENTER);
    emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    emptyTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), AndroidUtilities.dp(128));
    emptyView.addView(emptyTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 24, 0, 0));

    progressView = new LinearLayout(context);
    progressView.setGravity(Gravity.CENTER);
    progressView.setOrientation(LinearLayout.VERTICAL);
    progressView.setVisibility(View.GONE);
    progressView.setBackgroundColor(0xfff0f0f0);
    frameLayout.addView(progressView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    ProgressBar progressBar = new ProgressBar(context);
    progressView.addView(progressBar,
            LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));

    switchToCurrentSelectedMode();

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

    return fragmentView;
}

From source file:ir.irani.telecam.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, boolean needGif, final Context context) {
    super(context);

    showStickers = needStickers;//  w  w w .ja  va 2  s  . c om
    showGifs = needGif;

    for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        views.add(gridView);

        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
        gridView.setAdapter(emojiGridAdapter);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        adapters.add(emojiGridAdapter);
    }

    if (showStickers) {
        StickersQuery.checkStickers();
        stickersGridView = new GridView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        stickersGridView, EmojiView.this.getMeasuredHeight());
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public void setVisibility(int visibility) {
                if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE) {
                    super.setVisibility(GONE);
                    return;
                }
                super.setVisibility(visibility);
            }
        };
        stickersGridView.setSelector(R.drawable.transparent);
        stickersGridView.setColumnWidth(AndroidUtilities.dp(72));
        stickersGridView.setNumColumns(-1);
        stickersGridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersGridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        stickersGridView.setAdapter(stickersGridAdapter);
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView,
                        EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
            }
        });
        stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long i) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                StickerPreviewViewer.getInstance().reset();
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                TLRPC.Document document = cell.getSticker();
                addRecentSticker(document);
                if (listener != null) {
                    listener.onStickerSelected(document);
                }
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        AndroidUtilities.setListViewEdgeEffectColor(stickersGridView, 0xfff5f6f7);

        stickersWrap = new FrameLayout(context);
        stickersWrap.addView(stickersGridView);

        if (needGif) {
            gifsGridView = new RecyclerListView(context);
            gifsGridView.setTag(11);
            gifsGridView.setLayoutManager(flowLayoutManager = new ExtendedGridLayoutManager(context, 100) {

                private Size size = new Size();

                @Override
                protected Size getSizeForItem(int i) {
                    TLRPC.Document document = recentImages.get(i).document;
                    size.width = document.thumb != null && document.thumb.w != 0 ? document.thumb.w : 100;
                    size.height = document.thumb != null && document.thumb.h != 0 ? document.thumb.h : 100;
                    for (int b = 0; b < document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                    return size;
                }
            });
            flowLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return flowLayoutManager.getSpanSizeForItem(position);
                }
            });
            gifsGridView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent,
                        RecyclerView.State state) {
                    outRect.left = 0;
                    outRect.top = 0;
                    outRect.bottom = 0;
                    int position = parent.getChildAdapterPosition(view);
                    if (!flowLayoutManager.isFirstRow(position)) {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = flowLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            });
            gifsGridView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
            gifsGridView.setAdapter(gifsAdapter = new GifsAdapter(context));
            gifsGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size() || listener == null) {
                        return;
                    }
                    TLRPC.Document document = recentImages.get(position).document;
                    listener.onGifSelected(document);
                }
            });
            gifsGridView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
                @Override
                public boolean onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size()) {
                        return false;
                    }
                    final MediaController.SearchImage searchImage = recentImages.get(position);
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setMessage(LocaleController.getString("DeleteGif", R.string.DeleteGif));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK).toUpperCase(),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    recentImages.remove(searchImage);
                                    TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
                                    req.id = new TLRPC.TL_inputDocument();
                                    req.id.id = searchImage.document.id;
                                    req.id.access_hash = searchImage.document.access_hash;
                                    req.unsave = true;
                                    ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                                        @Override
                                        public void run(TLObject response, TLRPC.TL_error error) {

                                        }
                                    });
                                    MessagesStorage.getInstance().removeWebRecent(searchImage);
                                    if (gifsAdapter != null) {
                                        gifsAdapter.notifyDataSetChanged();
                                    }
                                    if (recentImages.isEmpty()) {
                                        updateStickerTabs();
                                    }
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    builder.show().setCanceledOnTouchOutside(true);
                    return true;
                }
            });
            gifsGridView.setVisibility(GONE);
            stickersWrap.addView(gifsGridView);
        }

        stickersEmptyView = new TextView(context);
        stickersEmptyView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
        stickersEmptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        stickersEmptyView.setTextColor(0xff888888);
        stickersWrap.addView(stickersEmptyView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        stickersGridView.setEmptyView(stickersEmptyView);

        scrollSlidingTabStrip = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (first) {
                    first = false;
                    lastX = ev.getX();
                }
                float newTranslationX = scrollSlidingTabStrip.getTranslationX();
                if (scrollSlidingTabStrip.getScrollX() == 0 && newTranslationX == 0) {
                    if (!startedScroll && lastX - ev.getX() < 0) {
                        if (pager.beginFakeDrag()) {
                            startedScroll = true;
                            lastTranslateX = scrollSlidingTabStrip.getTranslationX();
                        }
                    } else if (startedScroll && lastX - ev.getX() > 0) {
                        if (pager.isFakeDragging()) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                }
                if (startedScroll) {
                    int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                    try {
                        pager.fakeDragBy(dx);
                        lastTranslateX = newTranslationX;
                    } catch (Exception e) {
                        try {
                            pager.endFakeDrag();
                        } catch (Exception e2) {
                            //don't promt
                        }
                        startedScroll = false;
                        FileLog.e("tmessages", e);
                    }
                }
                lastX = ev.getX();
                if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
                    first = true;
                    if (startedScroll) {
                        pager.endFakeDrag();
                        startedScroll = false;
                    }
                }
                return startedScroll || super.onTouchEvent(ev);
            }
        };
        scrollSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
        scrollSlidingTabStrip.setIndicatorColor(0xffe2e5e7);
        scrollSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
        scrollSlidingTabStrip.setVisibility(INVISIBLE);
        addView(scrollSlidingTabStrip,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        scrollSlidingTabStrip.setTranslationX(AndroidUtilities.displaySize.x);
        updateStickerTabs();
        scrollSlidingTabStrip.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (gifsGridView != null) {
                    if (page == gifTabBum + 1) {
                        if (gifsGridView.getVisibility() != VISIBLE) {
                            listener.onGifTab(true);
                            showGifTab();
                        }
                    } else {
                        if (gifsGridView.getVisibility() == VISIBLE) {
                            listener.onGifTab(false);
                            gifsGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getCount() != 0 ? GONE : VISIBLE);
                        }
                    }
                }
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else {
                    if (page == gifTabBum + 1) {
                        return;
                    } else {
                        if (page == recentTabBum + 1) {
                            views.get(6).setSelection(0);
                            return;
                        }
                    }
                }
                int index = page - 1 - stickersTabOffset;
                if (index == stickerSets.size()) {
                    if (listener != null) {
                        listener.onStickersSettingsClick();
                    }
                    return;
                }
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
            }
        });

        stickersGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                checkStickersScroll(firstVisibleItem);
            }
        });
    }

    setBackgroundColor(0xfff5f6f7);

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    pagerSlidingTabStripContainer = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pagerSlidingTabStripContainer.setOrientation(LinearLayout.HORIZONTAL);
    pagerSlidingTabStripContainer.setBackgroundColor(0xfff5f6f7);
    addView(pagerSlidingTabStripContainer, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    PagerSlidingTabStrip pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    pagerSlidingTabStripContainer.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth(), positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    pagerSlidingTabStripContainer.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    recentsWrap = new FrameLayout(context);
    recentsWrap.addView(views.get(0));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    recentsWrap.addView(textView);
    views.get(0).setEmptyView(textView);

    addView(pager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP, 0, 48, 0, 0));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });

    loadRecents();
}

From source file:ir.besteveryeverapp.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, boolean needGif, final Context context) {
    super(context);

    showStickers = needStickers;/*w w w .  j a v a2 s  .  co m*/
    showGifs = needGif;

    for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        views.add(gridView);

        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
        gridView.setAdapter(emojiGridAdapter);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        adapters.add(emojiGridAdapter);
    }

    if (showStickers) {
        StickersQuery.checkStickers();
        stickersGridView = new GridView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        stickersGridView, EmojiView.this.getMeasuredHeight());
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public void setVisibility(int visibility) {
                if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE) {
                    super.setVisibility(GONE);
                    return;
                }
                super.setVisibility(visibility);
            }
        };
        stickersGridView.setSelector(R.drawable.transparent);
        stickersGridView.setColumnWidth(AndroidUtilities.dp(72));
        stickersGridView.setNumColumns(-1);
        stickersGridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersGridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        stickersGridView.setAdapter(stickersGridAdapter);
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView,
                        EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
            }
        });
        stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long i) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                StickerPreviewViewer.getInstance().reset();
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                TLRPC.Document document = cell.getSticker();
                addRecentSticker(document);
                if (listener != null) {
                    listener.onStickerSelected(document);
                }
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        AndroidUtilities.setListViewEdgeEffectColor(stickersGridView, 0xfff5f6f7);

        stickersWrap = new FrameLayout(context);
        stickersWrap.addView(stickersGridView);

        if (needGif) {
            gifsGridView = new RecyclerListView(context);
            gifsGridView.setTag(11);
            gifsGridView.setLayoutManager(flowLayoutManager = new ExtendedGridLayoutManager(context, 100) {

                private Size size = new Size();

                @Override
                protected Size getSizeForItem(int i) {
                    TLRPC.Document document = recentImages.get(i).document;
                    size.width = document.thumb != null && document.thumb.w != 0 ? document.thumb.w : 100;
                    size.height = document.thumb != null && document.thumb.h != 0 ? document.thumb.h : 100;
                    for (int b = 0; b < document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                    return size;
                }
            });
            flowLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return flowLayoutManager.getSpanSizeForItem(position);
                }
            });
            gifsGridView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent,
                        RecyclerView.State state) {
                    outRect.left = 0;
                    outRect.top = 0;
                    outRect.bottom = 0;
                    int position = parent.getChildAdapterPosition(view);
                    if (!flowLayoutManager.isFirstRow(position)) {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = flowLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            });
            gifsGridView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
            gifsGridView.setAdapter(gifsAdapter = new GifsAdapter(context));
            gifsGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size() || listener == null) {
                        return;
                    }
                    TLRPC.Document document = recentImages.get(position).document;
                    listener.onGifSelected(document);
                }
            });
            gifsGridView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
                @Override
                public boolean onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size()) {
                        return false;
                    }
                    final MediaController.SearchImage searchImage = recentImages.get(position);
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setMessage(LocaleController.getString("DeleteGif", R.string.DeleteGif));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK).toUpperCase(),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    recentImages.remove(searchImage);
                                    TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
                                    req.id = new TLRPC.TL_inputDocument();
                                    req.id.id = searchImage.document.id;
                                    req.id.access_hash = searchImage.document.access_hash;
                                    req.unsave = true;
                                    ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                                        @Override
                                        public void run(TLObject response, TLRPC.TL_error error) {

                                        }
                                    });
                                    MessagesStorage.getInstance().removeWebRecent(searchImage);
                                    if (gifsAdapter != null) {
                                        gifsAdapter.notifyDataSetChanged();
                                    }
                                    if (recentImages.isEmpty()) {
                                        updateStickerTabs();
                                    }
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    builder.show().setCanceledOnTouchOutside(true);
                    return true;
                }
            });
            gifsGridView.setVisibility(GONE);
            stickersWrap.addView(gifsGridView);
        }

        stickersEmptyView = new TextView(context);
        stickersEmptyView.setTypeface(FontManager.instance().getTypeface());
        stickersEmptyView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
        stickersEmptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        stickersEmptyView.setTextColor(0xff888888);
        stickersWrap.addView(stickersEmptyView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        stickersGridView.setEmptyView(stickersEmptyView);

        scrollSlidingTabStrip = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (first) {
                    first = false;
                    lastX = ev.getX();
                }
                float newTranslationX = scrollSlidingTabStrip.getTranslationX();
                if (scrollSlidingTabStrip.getScrollX() == 0 && newTranslationX == 0) {
                    if (!startedScroll && lastX - ev.getX() < 0) {
                        if (pager.beginFakeDrag()) {
                            startedScroll = true;
                            lastTranslateX = scrollSlidingTabStrip.getTranslationX();
                        }
                    } else if (startedScroll && lastX - ev.getX() > 0) {
                        if (pager.isFakeDragging()) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                }
                if (startedScroll) {
                    int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                    try {
                        pager.fakeDragBy(dx);
                        lastTranslateX = newTranslationX;
                    } catch (Exception e) {
                        try {
                            pager.endFakeDrag();
                        } catch (Exception e2) {
                            //don't promt
                        }
                        startedScroll = false;
                        FileLog.e("tmessages", e);
                    }
                }
                lastX = ev.getX();
                if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
                    first = true;
                    if (startedScroll) {
                        pager.endFakeDrag();
                        startedScroll = false;
                    }
                }
                return startedScroll || super.onTouchEvent(ev);
            }
        };
        scrollSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
        scrollSlidingTabStrip.setIndicatorColor(0xffe2e5e7);
        scrollSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
        scrollSlidingTabStrip.setVisibility(INVISIBLE);
        addView(scrollSlidingTabStrip,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        scrollSlidingTabStrip.setTranslationX(AndroidUtilities.displaySize.x);
        updateStickerTabs();
        scrollSlidingTabStrip.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (gifsGridView != null) {
                    if (page == gifTabBum + 1) {
                        if (gifsGridView.getVisibility() != VISIBLE) {
                            listener.onGifTab(true);
                            showGifTab();
                        }
                    } else {
                        if (gifsGridView.getVisibility() == VISIBLE) {
                            listener.onGifTab(false);
                            gifsGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getCount() != 0 ? GONE : VISIBLE);
                        }
                    }
                }
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else {
                    if (page == gifTabBum + 1) {
                        return;
                    } else {
                        if (page == recentTabBum + 1) {
                            views.get(6).setSelection(0);
                            return;
                        }
                    }
                }
                int index = page - 1 - stickersTabOffset;
                if (index == stickerSets.size()) {
                    if (listener != null) {
                        listener.onStickersSettingsClick();
                    }
                    return;
                }
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
            }
        });

        stickersGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                checkStickersScroll(firstVisibleItem);
            }
        });
    }

    setBackgroundColor(0xfff5f6f7);

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    pagerSlidingTabStripContainer = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pagerSlidingTabStripContainer.setOrientation(LinearLayout.HORIZONTAL);
    pagerSlidingTabStripContainer.setBackgroundColor(0xfff5f6f7);
    addView(pagerSlidingTabStripContainer, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    PagerSlidingTabStrip pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    pagerSlidingTabStripContainer.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth(), positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    pagerSlidingTabStripContainer.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    recentsWrap = new FrameLayout(context);
    recentsWrap.addView(views.get(0));

    TextView textView = new TextView(context);
    textView.setTypeface(FontManager.instance().getTypeface());
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    recentsWrap.addView(textView);
    views.get(0).setEmptyView(textView);

    addView(pager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP, 0, 48, 0, 0));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });

    loadRecents();
}

From source file:com.panahit.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, boolean needGif, final Context context) {
    super(context);

    showStickers = needStickers;//from  w w w . ja  va 2 s. c  o  m
    showGifs = needGif;

    for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        views.add(gridView);

        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
        gridView.setAdapter(emojiGridAdapter);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        adapters.add(emojiGridAdapter);
    }

    if (showStickers) {
        StickersQuery.checkStickers();
        stickersGridView = new GridView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        stickersGridView, EmojiView.this.getMeasuredHeight());
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public void setVisibility(int visibility) {
                if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE) {
                    super.setVisibility(GONE);
                    return;
                }
                super.setVisibility(visibility);
            }
        };
        stickersGridView.setSelector(R.drawable.transparent);
        stickersGridView.setColumnWidth(AndroidUtilities.dp(72));
        stickersGridView.setNumColumns(-1);
        stickersGridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersGridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        stickersGridView.setAdapter(stickersGridAdapter);
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView,
                        EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
            }
        });
        stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long i) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                StickerPreviewViewer.getInstance().reset();
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                TLRPC.Document document = cell.getSticker();
                int index = newRecentStickers.indexOf(document.id);
                if (index == -1) {
                    newRecentStickers.add(0, document.id);
                    if (newRecentStickers.size() > 20) {
                        newRecentStickers.remove(newRecentStickers.size() - 1);
                    }
                } else if (index != 0) {
                    newRecentStickers.remove(index);
                    newRecentStickers.add(0, document.id);
                }

                saveRecentStickers();
                if (listener != null) {
                    listener.onStickerSelected(document);
                }
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        AndroidUtilities.setListViewEdgeEffectColor(stickersGridView, 0xfff5f6f7);

        stickersWrap = new FrameLayout(context);
        stickersWrap.addView(stickersGridView);

        if (needGif) {
            gifsGridView = new RecyclerListView(context);
            gifsGridView.setLayoutManager(flowLayoutManager = new FlowLayoutManager() {

                private Size size = new Size();

                @Override
                protected Size getSizeForItem(int i) {
                    TLRPC.Document document = recentImages.get(i).document;
                    size.width = document.thumb != null && document.thumb.w != 0 ? document.thumb.w : 100;
                    size.height = document.thumb != null && document.thumb.h != 0 ? document.thumb.h : 100;
                    for (int b = 0; b < document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                    return size;
                }
            });
            if (Build.VERSION.SDK_INT >= 9) {
                gifsGridView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
            }
            gifsGridView.setAdapter(gifsAdapter = new GifsAdapter(context));
            gifsGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size() || listener == null) {
                        return;
                    }
                    TLRPC.Document document = recentImages.get(position).document;
                    listener.onStickerSelected(document);
                }
            });
            gifsGridView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
                @Override
                public boolean onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size()) {
                        return false;
                    }
                    final MediaController.SearchImage searchImage = recentImages.get(position);
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setMessage(LocaleController.getString("DeleteGif", R.string.DeleteGif));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK).toUpperCase(),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    recentImages.remove(searchImage);
                                    TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
                                    req.id = new TLRPC.TL_inputDocument();
                                    req.id.id = searchImage.document.id;
                                    req.id.access_hash = searchImage.document.access_hash;
                                    req.unsave = true;
                                    ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                                        @Override
                                        public void run(TLObject response, TLRPC.TL_error error) {

                                        }
                                    });
                                    MessagesStorage.getInstance().removeWebRecent(searchImage);
                                    if (gifsAdapter != null) {
                                        gifsAdapter.notifyDataSetChanged();
                                    }
                                    if (recentImages.isEmpty()) {
                                        updateStickerTabs();
                                    }
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    builder.show().setCanceledOnTouchOutside(true);
                    return true;
                }
            });
            gifsGridView.setVisibility(GONE);
            stickersWrap.addView(gifsGridView);
        }

        stickersEmptyView = new TextView(context);
        stickersEmptyView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
        stickersEmptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        stickersEmptyView.setTextColor(0xff888888);
        stickersWrap.addView(stickersEmptyView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        stickersGridView.setEmptyView(stickersEmptyView);

        scrollSlidingTabStrip = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (Build.VERSION.SDK_INT >= 11) {
                    if (first) {
                        first = false;
                        lastX = ev.getX();
                    }
                    float newTranslationX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
                    if (scrollSlidingTabStrip.getScrollX() == 0 && newTranslationX == 0) {
                        if (!startedScroll && lastX - ev.getX() < 0) {
                            if (pager.beginFakeDrag()) {
                                startedScroll = true;
                                lastTranslateX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
                            }
                        } else if (startedScroll && lastX - ev.getX() > 0) {
                            if (pager.isFakeDragging()) {
                                pager.endFakeDrag();
                                startedScroll = false;
                            }
                        }
                    }
                    if (startedScroll) {
                        int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                        try {
                            pager.fakeDragBy(dx);
                            lastTranslateX = newTranslationX;
                        } catch (Exception e) {
                            try {
                                pager.endFakeDrag();
                            } catch (Exception e2) {
                                //don't promt
                            }
                            startedScroll = false;
                            FileLog.e("tmessages", e);
                        }
                    }
                    lastX = ev.getX();
                    if (ev.getAction() == MotionEvent.ACTION_CANCEL
                            || ev.getAction() == MotionEvent.ACTION_UP) {
                        first = true;
                        if (startedScroll) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                    return startedScroll || super.onTouchEvent(ev);
                }
                return super.onTouchEvent(ev);
            }
        };
        scrollSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
        scrollSlidingTabStrip.setIndicatorColor(0xffe2e5e7);
        scrollSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
        scrollSlidingTabStrip.setVisibility(INVISIBLE);
        addView(scrollSlidingTabStrip,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        ViewProxy.setTranslationX(scrollSlidingTabStrip, AndroidUtilities.displaySize.x);
        updateStickerTabs();
        scrollSlidingTabStrip.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (gifsGridView != null) {
                    if (page == gifTabBum + 1) {
                        if (gifsGridView.getVisibility() != VISIBLE) {
                            listener.onGifTab(true);
                            showGifTab();
                        }
                    } else {
                        if (gifsGridView.getVisibility() == VISIBLE) {
                            listener.onGifTab(false);
                            gifsGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getCount() != 0 ? GONE : VISIBLE);
                        }
                    }
                }
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else {
                    if (page == gifTabBum + 1) {
                        return;
                    } else {
                        if (page == recentTabBum + 1) {
                            views.get(6).setSelection(0);
                            return;
                        }
                    }
                }
                int index = page - 1 - stickersTabOffset;
                if (index == stickerSets.size()) {
                    if (listener != null) {
                        listener.onStickersSettingsClick();
                    }
                    return;
                }
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
            }
        });

        stickersGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                checkStickersScroll(firstVisibleItem);
            }
        });
    }

    setBackgroundColor(0xfff5f6f7);

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    pagerSlidingTabStripContainer = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pagerSlidingTabStripContainer.setOrientation(LinearLayout.HORIZONTAL);
    pagerSlidingTabStripContainer.setBackgroundColor(0xfff5f6f7);
    addView(pagerSlidingTabStripContainer, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    PagerSlidingTabStrip pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    pagerSlidingTabStripContainer.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth(), positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    pagerSlidingTabStripContainer.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    recentsWrap = new FrameLayout(context);
    recentsWrap.addView(views.get(0));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    recentsWrap.addView(textView);
    views.get(0).setEmptyView(textView);

    addView(pager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP, 0, 48, 0, 0));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });

    loadRecents();
}

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

@Override
public View createView(Context context) {
    Log.d(LOG_TAG, "createView");
    actionBar.setBackButtonDrawable(new BackDrawable(false));
    actionBar.setTitle("");
    actionBar.setAllowOverlayTitle(false);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override/* w  w w. j ava2  s.com*/
        public void onItemClick(int id) {
            if (id == -1) {
                if (actionBar.isActionModeShowed()) {
                    for (int a = 1; a >= 0; a--) {
                        selectedFiles[a].clear();
                    }
                    cantDeleteMessagesCount = 0;
                    actionBar.hideActionMode();
                    listView.invalidateViews();
                } else {
                    finishFragment();
                }
            } else if (id == shared_media_item) {
                if (selectedMode == 0) {
                    return;
                }
                selectedMode = 0;
                switchToCurrentSelectedMode();
            } else if (id == files_item) {
                if (selectedMode == 1) {
                    return;
                }
                selectedMode = 1;
                switchToCurrentSelectedMode();
            } else if (id == links_item) {
                if (selectedMode == 3) {
                    return;
                }
                selectedMode = 3;
                switchToCurrentSelectedMode();
            } else if (id == music_item) {
                if (selectedMode == 4) {
                    return;
                }
                selectedMode = 4;
                switchToCurrentSelectedMode();
            } else if (id == delete) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(LocaleController.formatString("AreYouSureDeleteMessages",
                        kr.wdream.storyshop.R.string.AreYouSureDeleteMessages,
                        LocaleController.formatPluralString("items",
                                selectedFiles[0].size() + selectedFiles[1].size())));
                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) {
                                for (int a = 1; a >= 0; a--) {
                                    ArrayList<Integer> ids = new ArrayList<>(selectedFiles[a].keySet());
                                    ArrayList<Long> random_ids = null;
                                    TLRPC.EncryptedChat currentEncryptedChat = null;
                                    int channelId = 0;
                                    if (!ids.isEmpty()) {
                                        MessageObject msg = selectedFiles[a].get(ids.get(0));
                                        if (channelId == 0 && msg.messageOwner.to_id.channel_id != 0) {
                                            channelId = msg.messageOwner.to_id.channel_id;
                                        }
                                    }
                                    if ((int) dialog_id == 0) {
                                        currentEncryptedChat = MessagesController.getInstance()
                                                .getEncryptedChat((int) (dialog_id >> 32));
                                    }
                                    if (currentEncryptedChat != null) {
                                        random_ids = new ArrayList<>();
                                        for (HashMap.Entry<Integer, MessageObject> entry : selectedFiles[a]
                                                .entrySet()) {
                                            MessageObject msg = entry.getValue();
                                            if (msg.messageOwner.random_id != 0 && msg.type != 10) {
                                                random_ids.add(msg.messageOwner.random_id);
                                            }
                                        }
                                    }
                                    MessagesController.getInstance().deleteMessages(ids, random_ids,
                                            currentEncryptedChat, channelId);
                                    selectedFiles[a].clear();
                                }
                                actionBar.hideActionMode();
                                actionBar.closeSearchField();
                                cantDeleteMessagesCount = 0;
                            }
                        });
                builder.setNegativeButton(
                        LocaleController.getString("Cancel", kr.wdream.storyshop.R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == forward) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() {
                    @Override
                    public void didSelectDialog(DialogsActivity fragment, long did, boolean param) {
                        int lower_part = (int) did;
                        if (lower_part != 0) {
                            Bundle args = new Bundle();
                            args.putBoolean("scrollToTopOnResume", true);
                            if (lower_part > 0) {
                                args.putInt("user_id", lower_part);
                            } else if (lower_part < 0) {
                                args.putInt("chat_id", -lower_part);
                            }
                            if (!MessagesController.checkCanOpenChat(args, fragment)) {
                                return;
                            }

                            ArrayList<MessageObject> fmessages = new ArrayList<>();
                            for (int a = 1; a >= 0; a--) {
                                ArrayList<Integer> ids = new ArrayList<>(selectedFiles[a].keySet());
                                Collections.sort(ids);
                                for (Integer id : ids) {
                                    if (id > 0) {
                                        fmessages.add(selectedFiles[a].get(id));
                                    }
                                }
                                selectedFiles[a].clear();
                            }
                            cantDeleteMessagesCount = 0;
                            actionBar.hideActionMode();

                            NotificationCenter.getInstance()
                                    .postNotificationName(NotificationCenter.closeChats);

                            ChatActivity chatActivity = new ChatActivity(args);
                            presentFragment(chatActivity, true);
                            chatActivity.showReplyPanel(true, null, fmessages, null, false, false);

                            if (!AndroidUtilities.isTablet()) {
                                removeSelfFromStack();
                            }
                        } else {
                            fragment.finishFragment();
                        }
                    }
                });
                presentFragment(fragment);
            }
        }
    });

    for (int a = 1; a >= 0; a--) {
        selectedFiles[a].clear();
    }
    cantDeleteMessagesCount = 0;
    actionModeViews.clear();

    final ActionBarMenu menu = actionBar.createMenu();
    searchItem = menu.addItem(0, kr.wdream.storyshop.R.drawable.ic_ab_search).setIsSearchField(true)
            .setActionBarMenuItemSearchListener(new ActionBarMenuItem.ActionBarMenuItemSearchListener() {
                @Override
                public void onSearchExpand() {
                    dropDownContainer.setVisibility(View.GONE);
                    searching = true;
                }

                @Override
                public void onSearchCollapse() {
                    dropDownContainer.setVisibility(View.VISIBLE);
                    if (selectedMode == 1) {
                        documentsSearchAdapter.search(null);
                    } else if (selectedMode == 3) {
                        linksSearchAdapter.search(null);
                    } else if (selectedMode == 4) {
                        audioSearchAdapter.search(null);
                    }
                    searching = false;
                    searchWas = false;
                    switchToCurrentSelectedMode();
                }

                @Override
                public void onTextChanged(EditText editText) {
                    String text = editText.getText().toString();
                    if (text.length() != 0) {
                        searchWas = true;
                        switchToCurrentSelectedMode();
                    }
                    if (selectedMode == 1) {
                        if (documentsSearchAdapter == null) {
                            return;
                        }
                        documentsSearchAdapter.search(text);
                    } else if (selectedMode == 3) {
                        if (linksSearchAdapter == null) {
                            return;
                        }
                        linksSearchAdapter.search(text);
                    } else if (selectedMode == 4) {
                        if (audioSearchAdapter == null) {
                            return;
                        }
                        audioSearchAdapter.search(text);
                    }
                }
            });
    searchItem.getSearchField()
            .setHint(LocaleController.getString("Search", kr.wdream.storyshop.R.string.Search));
    searchItem.setVisibility(View.GONE);

    dropDownContainer = new ActionBarMenuItem(context, menu, 0);
    dropDownContainer.setSubMenuOpenSide(1);
    dropDownContainer.addSubItem(shared_media_item,
            LocaleController.getString("SharedMediaTitle", kr.wdream.storyshop.R.string.SharedMediaTitle), 0);
    dropDownContainer.addSubItem(files_item,
            LocaleController.getString("DocumentsTitle", kr.wdream.storyshop.R.string.DocumentsTitle), 0);
    if ((int) dialog_id != 0) {
        dropDownContainer.addSubItem(links_item,
                LocaleController.getString("LinksTitle", kr.wdream.storyshop.R.string.LinksTitle), 0);
        dropDownContainer.addSubItem(music_item,
                LocaleController.getString("AudioTitle", kr.wdream.storyshop.R.string.AudioTitle), 0);
    } else {
        TLRPC.EncryptedChat currentEncryptedChat = MessagesController.getInstance()
                .getEncryptedChat((int) (dialog_id >> 32));
        if (currentEncryptedChat != null
                && AndroidUtilities.getPeerLayerVersion(currentEncryptedChat.layer) >= 46) {
            dropDownContainer.addSubItem(music_item,
                    LocaleController.getString("AudioTitle", kr.wdream.storyshop.R.string.AudioTitle), 0);
        }
    }
    actionBar.addView(dropDownContainer, 0,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT,
                    Gravity.TOP | Gravity.LEFT, AndroidUtilities.isTablet() ? 64 : 56, 0, 40, 0));
    dropDownContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dropDownContainer.toggleSubMenu();
        }
    });

    dropDown = new TextView(context);
    dropDown.setGravity(Gravity.LEFT);
    dropDown.setSingleLine(true);
    dropDown.setLines(1);
    dropDown.setMaxLines(1);
    dropDown.setEllipsize(TextUtils.TruncateAt.END);
    dropDown.setTextColor(0xffffffff);
    dropDown.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    dropDown.setCompoundDrawablesWithIntrinsicBounds(0, 0, kr.wdream.storyshop.R.drawable.ic_arrow_drop_down,
            0);
    dropDown.setCompoundDrawablePadding(AndroidUtilities.dp(4));
    dropDown.setPadding(0, 0, AndroidUtilities.dp(10), 0);
    dropDownContainer.addView(dropDown, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, 16, 0, 0, 0));

    final ActionBarMenu actionMode = actionBar.createActionMode();

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

    if ((int) dialog_id != 0) {
        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)));

    photoVideoAdapter = new SharedPhotoVideoAdapter(context);
    documentsAdapter = new SharedDocumentsAdapter(context, 1);
    audioAdapter = new SharedDocumentsAdapter(context, 4);
    documentsSearchAdapter = new MediaSearchAdapter(context, 1);
    audioSearchAdapter = new MediaSearchAdapter(context, 4);
    linksSearchAdapter = new MediaSearchAdapter(context, 3);
    linksAdapter = new SharedLinksAdapter(context);

    FrameLayout frameLayout;
    fragmentView = frameLayout = new FrameLayout(context);

    listView = new SectionsListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setDrawSelectorOnTop(true);
    listView.setClipToPadding(false);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
            if ((selectedMode == 1 || selectedMode == 4) && view instanceof SharedDocumentCell) {
                MediaActivity.this.onItemClick(i, view, ((SharedDocumentCell) view).getMessage(), 0);
            } else if (selectedMode == 3 && view instanceof SharedLinkCell) {
                MediaActivity.this.onItemClick(i, view, ((SharedLinkCell) view).getMessage(), 0);
            }
        }
    });
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if (scrollState == SCROLL_STATE_TOUCH_SCROLL && searching && searchWas) {
                AndroidUtilities.hideKeyboard(getParentActivity().getCurrentFocus());
            }
            scrolling = scrollState != SCROLL_STATE_IDLE;
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (searching && searchWas) {
                return;
            }
            if (visibleItemCount != 0 && firstVisibleItem + visibleItemCount > totalItemCount - 2
                    && !sharedMediaData[selectedMode].loading) {
                int type;
                if (selectedMode == 0) {
                    type = SharedMediaQuery.MEDIA_PHOTOVIDEO;
                } else if (selectedMode == 1) {
                    type = SharedMediaQuery.MEDIA_FILE;
                } else if (selectedMode == 2) {
                    type = SharedMediaQuery.MEDIA_AUDIO;
                } else if (selectedMode == 4) {
                    type = SharedMediaQuery.MEDIA_MUSIC;
                } else {
                    type = SharedMediaQuery.MEDIA_URL;
                }
                if (!sharedMediaData[selectedMode].endReached[0]) {
                    sharedMediaData[selectedMode].loading = true;
                    SharedMediaQuery.loadMedia(dialog_id, 0, 50, sharedMediaData[selectedMode].max_id[0], type,
                            true, classGuid);
                } else if (mergeDialogId != 0 && !sharedMediaData[selectedMode].endReached[1]) {
                    sharedMediaData[selectedMode].loading = true;
                    SharedMediaQuery.loadMedia(mergeDialogId, 0, 50, sharedMediaData[selectedMode].max_id[1],
                            type, true, classGuid);
                }
            }
        }
    });
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long id) {
            if ((selectedMode == 1 || selectedMode == 4) && view instanceof SharedDocumentCell) {
                SharedDocumentCell cell = (SharedDocumentCell) view;
                MessageObject message = cell.getMessage();
                return MediaActivity.this.onItemLongClick(message, view, 0);
            } else if (selectedMode == 3 && view instanceof SharedLinkCell) {
                SharedLinkCell cell = (SharedLinkCell) view;
                MessageObject message = cell.getMessage();
                return MediaActivity.this.onItemLongClick(message, view, 0);
            }
            return false;
        }
    });

    for (int a = 0; a < 6; a++) {
        cellCache.add(new SharedPhotoVideoCell(context));
    }

    emptyView = new LinearLayout(context);
    emptyView.setOrientation(LinearLayout.VERTICAL);
    emptyView.setGravity(Gravity.CENTER);
    emptyView.setVisibility(View.GONE);
    emptyView.setBackgroundColor(0xfff0f0f0);
    frameLayout.addView(emptyView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    emptyView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    emptyImageView = new ImageView(context);
    emptyView.addView(emptyImageView,
            LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));

    emptyTextView = new TextView(context);
    emptyTextView.setTextColor(0xff8a8a8a);
    emptyTextView.setGravity(Gravity.CENTER);
    emptyTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 17);
    emptyTextView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), AndroidUtilities.dp(128));
    emptyView.addView(emptyTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT,
            LayoutHelper.WRAP_CONTENT, Gravity.CENTER, 0, 24, 0, 0));

    progressView = new LinearLayout(context);
    progressView.setGravity(Gravity.CENTER);
    progressView.setOrientation(LinearLayout.VERTICAL);
    progressView.setVisibility(View.GONE);
    progressView.setBackgroundColor(0xfff0f0f0);
    frameLayout.addView(progressView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    ProgressBar progressBar = new ProgressBar(context);
    progressView.addView(progressBar,
            LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT));

    switchToCurrentSelectedMode();

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

    return fragmentView;
}

From source file:org.cafemember.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, boolean needGif, final Context context) {
    super(context);

    showStickers = needStickers;//from   www  .j ava  2 s. c om
    showGifs = needGif;

    for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        views.add(gridView);

        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
        gridView.setAdapter(emojiGridAdapter);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        adapters.add(emojiGridAdapter);
    }

    if (showStickers) {
        StickersQuery.checkStickers();
        stickersGridView = new GridView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        stickersGridView, EmojiView.this.getMeasuredHeight());
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public void setVisibility(int visibility) {
                if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE) {
                    super.setVisibility(GONE);
                    return;
                }
                super.setVisibility(visibility);
            }
        };
        stickersGridView.setSelector(R.drawable.transparent);
        stickersGridView.setColumnWidth(AndroidUtilities.dp(72));
        stickersGridView.setNumColumns(-1);
        stickersGridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersGridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        stickersGridView.setAdapter(stickersGridAdapter);
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView,
                        EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
            }
        });
        stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long i) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                StickerPreviewViewer.getInstance().reset();
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                TLRPC.Document document = cell.getSticker();
                int index = newRecentStickers.indexOf(document.id);
                if (index == -1) {
                    newRecentStickers.add(0, document.id);
                    if (newRecentStickers.size() > 20) {
                        newRecentStickers.remove(newRecentStickers.size() - 1);
                    }
                } else if (index != 0) {
                    newRecentStickers.remove(index);
                    newRecentStickers.add(0, document.id);
                }

                saveRecentStickers();
                if (listener != null) {
                    listener.onStickerSelected(document);
                }
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        AndroidUtilities.setListViewEdgeEffectColor(stickersGridView, 0xfff5f6f7);

        stickersWrap = new FrameLayout(context);
        stickersWrap.addView(stickersGridView);

        if (needGif) {
            gifsGridView = new RecyclerListView(context);
            gifsGridView.setLayoutManager(flowLayoutManager = new FlowLayoutManager() {

                private Size size = new Size();

                @Override
                protected Size getSizeForItem(int i) {
                    TLRPC.Document document = recentImages.get(i).document;
                    size.width = document.thumb != null && document.thumb.w != 0 ? document.thumb.w : 100;
                    size.height = document.thumb != null && document.thumb.h != 0 ? document.thumb.h : 100;
                    for (int b = 0; b < document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                    return size;
                }
            });
            if (Build.VERSION.SDK_INT >= 9) {
                gifsGridView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
            }
            gifsGridView.setAdapter(gifsAdapter = new GifsAdapter(context));
            gifsGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size() || listener == null) {
                        return;
                    }
                    TLRPC.Document document = recentImages.get(position).document;
                    listener.onGifSelected(document);
                }
            });
            gifsGridView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
                @Override
                public boolean onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size()) {
                        return false;
                    }
                    final MediaController.SearchImage searchImage = recentImages.get(position);
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                    builder.setMessage(LocaleController.getString("DeleteGif", R.string.DeleteGif));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK).toUpperCase(),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    recentImages.remove(searchImage);
                                    TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
                                    req.id = new TLRPC.TL_inputDocument();
                                    req.id.id = searchImage.document.id;
                                    req.id.access_hash = searchImage.document.access_hash;
                                    req.unsave = true;
                                    ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                                        @Override
                                        public void run(TLObject response, TLRPC.TL_error error) {

                                        }
                                    });
                                    MessagesStorage.getInstance().removeWebRecent(searchImage);
                                    if (gifsAdapter != null) {
                                        gifsAdapter.notifyDataSetChanged();
                                    }
                                    if (recentImages.isEmpty()) {
                                        updateStickerTabs();
                                    }
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    builder.show().setCanceledOnTouchOutside(true);
                    return true;
                }
            });
            gifsGridView.setVisibility(GONE);
            stickersWrap.addView(gifsGridView);
        }

        stickersEmptyView = new TextView(context);
        stickersEmptyView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
        stickersEmptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        stickersEmptyView.setTextColor(0xff888888);
        stickersWrap.addView(stickersEmptyView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        stickersGridView.setEmptyView(stickersEmptyView);

        scrollSlidingTabStrip = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (Build.VERSION.SDK_INT >= 11) {
                    if (first) {
                        first = false;
                        lastX = ev.getX();
                    }
                    float newTranslationX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
                    if (scrollSlidingTabStrip.getScrollX() == 0 && newTranslationX == 0) {
                        if (!startedScroll && lastX - ev.getX() < 0) {
                            if (pager.beginFakeDrag()) {
                                startedScroll = true;
                                lastTranslateX = ViewProxy.getTranslationX(scrollSlidingTabStrip);
                            }
                        } else if (startedScroll && lastX - ev.getX() > 0) {
                            if (pager.isFakeDragging()) {
                                pager.endFakeDrag();
                                startedScroll = false;
                            }
                        }
                    }
                    if (startedScroll) {
                        int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                        try {
                            pager.fakeDragBy(dx);
                            lastTranslateX = newTranslationX;
                        } catch (Exception e) {
                            try {
                                pager.endFakeDrag();
                            } catch (Exception e2) {
                                //don't promt
                            }
                            startedScroll = false;
                            FileLog.e("tmessages", e);
                        }
                    }
                    lastX = ev.getX();
                    if (ev.getAction() == MotionEvent.ACTION_CANCEL
                            || ev.getAction() == MotionEvent.ACTION_UP) {
                        first = true;
                        if (startedScroll) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                    return startedScroll || super.onTouchEvent(ev);
                }
                return super.onTouchEvent(ev);
            }
        };
        scrollSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
        scrollSlidingTabStrip.setIndicatorColor(0xffe2e5e7);
        scrollSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
        scrollSlidingTabStrip.setVisibility(INVISIBLE);
        addView(scrollSlidingTabStrip,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        ViewProxy.setTranslationX(scrollSlidingTabStrip, AndroidUtilities.displaySize.x);
        updateStickerTabs();
        scrollSlidingTabStrip.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (gifsGridView != null) {
                    if (page == gifTabBum + 1) {
                        if (gifsGridView.getVisibility() != VISIBLE) {
                            listener.onGifTab(true);
                            showGifTab();
                        }
                    } else {
                        if (gifsGridView.getVisibility() == VISIBLE) {
                            listener.onGifTab(false);
                            gifsGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getCount() != 0 ? GONE : VISIBLE);
                        }
                    }
                }
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else {
                    if (page == gifTabBum + 1) {
                        return;
                    } else {
                        if (page == recentTabBum + 1) {
                            views.get(6).setSelection(0);
                            return;
                        }
                    }
                }
                int index = page - 1 - stickersTabOffset;
                if (index == stickerSets.size()) {
                    if (listener != null) {
                        listener.onStickersSettingsClick();
                    }
                    return;
                }
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
            }
        });

        stickersGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                checkStickersScroll(firstVisibleItem);
            }
        });
    }

    setBackgroundColor(0xfff5f6f7);

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    pagerSlidingTabStripContainer = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pagerSlidingTabStripContainer.setOrientation(LinearLayout.HORIZONTAL);
    pagerSlidingTabStripContainer.setBackgroundColor(0xfff5f6f7);
    addView(pagerSlidingTabStripContainer, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    PagerSlidingTabStrip pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    pagerSlidingTabStripContainer.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth(), positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    pagerSlidingTabStripContainer.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    recentsWrap = new FrameLayout(context);
    recentsWrap.addView(views.get(0));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    recentsWrap.addView(textView);
    views.get(0).setEmptyView(textView);

    addView(pager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP, 0, 48, 0, 0));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });

    loadRecents();
}

From source file:com.heneryh.aquanotes.ui.controllers.ControllersActivity.java

/**
 * Build and add "notes" tab.// www  .  j  a  va2 s . com
 */
private void setupNotesTab(Ctlr ctlr) {

    /**
     * nearly all of the comments here are the same as for the probes.
     */
    String tagSpec = TAG_NOTES + "_" + ctlr.mControllerId.toString().replace('-', 'n');
    int Rid;
    switch (ctlr.index) {
    case 0:
        Rid = R.id.fragment_notes_0;
        break;
    case 1:
        Rid = R.id.fragment_notes_1;
        break;
    case 2:
        Rid = R.id.fragment_notes_2;
        break;
    case 3:
        Rid = R.id.fragment_notes_3;
        break;
    case 4:
        Rid = R.id.fragment_notes_4;
        break;
    case 5:
        Rid = R.id.fragment_notes_5;
        break;
    case 6:
        Rid = R.id.fragment_notes_6;
        break;
    case 7:
        Rid = R.id.fragment_notes_7;
        break;
    case 8:
        Rid = R.id.fragment_notes_8;
        break;
    case 9:
        Rid = R.id.fragment_notes_9;
        break;
    default:
        Rid = 0;
    }

    /**
     * Build the intent that will be sent to the fragment
     */
    final Intent intent = new Intent(Intent.ACTION_VIEW,
            Controllers.buildQueryControllerXUri(ctlr.mControllerId));
    intent.putExtra("ControllerName", ctlr.mTitleString);

    ctlr.notesFragmentContainer = new FrameLayout(this);
    ctlr.notesFragmentContainer.setId(Rid);
    ViewGroup tabContentView = (ViewGroup) ctlr.mRootView.findViewById(android.R.id.tabcontent);
    tabContentView.addView(ctlr.notesFragmentContainer);

    final FragmentManager fm = getSupportFragmentManager();

    ctlr.mNotesFragment = (NotesFragment) fm.findFragmentByTag(tagSpec);
    if (ctlr.mNotesFragment == null) {
        ctlr.mNotesFragment = new NotesFragment();
        ctlr.mNotesFragment.setArguments(intentToFragmentArguments(intent));
        fm.beginTransaction().add(Rid, ctlr.mNotesFragment, tagSpec).commit();
    }

    ctlr.mTabHost.addTab(ctlr.mTabHost.newTabSpec(tagSpec)
            .setIndicator(buildIndicator(ctlr, R.string.notes_tab_title)).setContent(Rid));

}

From source file:com.b44t.ui.Components.EmojiView.java

public EmojiView(boolean needStickers, boolean needGif, final Context context) {
    super(context);

    showStickers = needStickers;//  ww w . j  a v a  2  s .c o  m
    showGifs = needGif;

    for (int i = 0; i < EmojiData.dataColored.length + 1; i++) {
        GridView gridView = new GridView(context);
        if (AndroidUtilities.isTablet()) {
            gridView.setColumnWidth(AndroidUtilities.dp(60));
        } else {
            gridView.setColumnWidth(AndroidUtilities.dp(45));
        }
        gridView.setNumColumns(-1);
        views.add(gridView);

        EmojiGridAdapter emojiGridAdapter = new EmojiGridAdapter(i - 1);
        gridView.setAdapter(emojiGridAdapter);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        adapters.add(emojiGridAdapter);
    }

    if (showStickers) {
        //StickersQuery.checkStickers();
        stickersGridView = new GridView(context) {
            @Override
            public boolean onInterceptTouchEvent(MotionEvent event) {
                boolean result = StickerPreviewViewer.getInstance().onInterceptTouchEvent(event,
                        stickersGridView, EmojiView.this.getMeasuredHeight());
                return super.onInterceptTouchEvent(event) || result;
            }

            @Override
            public void setVisibility(int visibility) {
                if (gifsGridView != null && gifsGridView.getVisibility() == VISIBLE) {
                    super.setVisibility(GONE);
                    return;
                }
                super.setVisibility(visibility);
            }
        };
        stickersGridView.setSelector(R.drawable.transparent);
        stickersGridView.setColumnWidth(AndroidUtilities.dp(72));
        stickersGridView.setNumColumns(-1);
        stickersGridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        stickersGridView.setClipToPadding(false);
        views.add(stickersGridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        stickersGridView.setAdapter(stickersGridAdapter);
        stickersGridView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return StickerPreviewViewer.getInstance().onTouch(event, stickersGridView,
                        EmojiView.this.getMeasuredHeight(), stickersOnItemClickListener);
            }
        });
        stickersOnItemClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long i) {
                if (!(view instanceof StickerEmojiCell)) {
                    return;
                }
                StickerPreviewViewer.getInstance().reset();
                StickerEmojiCell cell = (StickerEmojiCell) view;
                if (cell.isDisabled()) {
                    return;
                }
                cell.disable();
                TLRPC.Document document = cell.getSticker();
                addRecentSticker(document);
                if (listener != null) {
                    listener.onStickerSelected(document);
                }
            }
        };
        stickersGridView.setOnItemClickListener(stickersOnItemClickListener);
        AndroidUtilities.setListViewEdgeEffectColor(stickersGridView, 0xfff5f6f7);

        stickersWrap = new FrameLayout(context);
        stickersWrap.addView(stickersGridView);

        if (needGif) {
            gifsGridView = new RecyclerListView(context);
            gifsGridView.setTag(11);
            gifsGridView.setLayoutManager(flowLayoutManager = new ExtendedGridLayoutManager(context, 100) {

                private Size size = new Size();

                @Override
                protected Size getSizeForItem(int i) {
                    TLRPC.Document document = recentImages.get(i).document;
                    size.width = document.thumb != null && document.thumb.w != 0 ? document.thumb.w : 100;
                    size.height = document.thumb != null && document.thumb.h != 0 ? document.thumb.h : 100;
                    for (int b = 0; b < document.attributes.size(); b++) {
                        TLRPC.DocumentAttribute attribute = document.attributes.get(b);
                        if (attribute instanceof TLRPC.TL_documentAttributeImageSize
                                || attribute instanceof TLRPC.TL_documentAttributeVideo) {
                            size.width = attribute.w;
                            size.height = attribute.h;
                            break;
                        }
                    }
                    return size;
                }
            });
            flowLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    return flowLayoutManager.getSpanSizeForItem(position);
                }
            });
            gifsGridView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void getItemOffsets(android.graphics.Rect outRect, View view, RecyclerView parent,
                        RecyclerView.State state) {
                    outRect.left = 0;
                    outRect.top = 0;
                    outRect.bottom = 0;
                    int position = parent.getChildAdapterPosition(view);
                    if (!flowLayoutManager.isFirstRow(position)) {
                        outRect.top = AndroidUtilities.dp(2);
                    }
                    outRect.right = flowLayoutManager.isLastInRow(position) ? 0 : AndroidUtilities.dp(2);
                }
            });
            gifsGridView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
            gifsGridView.setAdapter(gifsAdapter = new GifsAdapter(context));
            gifsGridView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size() || listener == null) {
                        return;
                    }
                    TLRPC.Document document = recentImages.get(position).document;
                    listener.onGifSelected(document);
                }
            });
            gifsGridView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
                @Override
                public boolean onItemClick(View view, int position) {
                    if (position < 0 || position >= recentImages.size()) {
                        return false;
                    }
                    final MediaController.SearchImage searchImage = recentImages.get(position);
                    AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
                    builder.setMessage(LocaleController.getString("DeleteGif", R.string.DeleteGif));
                    builder.setPositiveButton(LocaleController.getString("OK", R.string.OK).toUpperCase(),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    recentImages.remove(searchImage);
                                    /*TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif();
                                    req.id = new TLRPC.TL_inputDocument();
                                    req.id.id = searchImage.document.id;
                                    req.id.access_hash = searchImage.document.access_hash;
                                    req.unsave = true;
                                    ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                                    @Override
                                    public void run(TLObject response, TLRPC.TL_error error) {
                                            
                                    }
                                    });*/
                                    //MessagesStorage.getInstance().removeWebRecent(searchImage);
                                    if (gifsAdapter != null) {
                                        gifsAdapter.notifyDataSetChanged();
                                    }
                                    if (recentImages.isEmpty()) {
                                        updateStickerTabs();
                                    }
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    builder.show().setCanceledOnTouchOutside(true);
                    return true;
                }
            });
            gifsGridView.setVisibility(GONE);
            stickersWrap.addView(gifsGridView);
        }

        stickersEmptyView = new TextView(context);
        stickersEmptyView.setText(LocaleController.getString("NoStickers", R.string.NoStickers));
        stickersEmptyView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        stickersEmptyView.setTextColor(0xff888888);
        stickersWrap.addView(stickersEmptyView,
                LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
        stickersGridView.setEmptyView(stickersEmptyView);

        scrollSlidingTabStrip = new ScrollSlidingTabStrip(context) {

            boolean startedScroll;
            float lastX;
            float lastTranslateX;
            boolean first = true;

            @Override
            public boolean onInterceptTouchEvent(MotionEvent ev) {
                if (getParent() != null) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.onInterceptTouchEvent(ev);
            }

            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                if (first) {
                    first = false;
                    lastX = ev.getX();
                }
                float newTranslationX = scrollSlidingTabStrip.getTranslationX();
                if (scrollSlidingTabStrip.getScrollX() == 0 && newTranslationX == 0) {
                    if (!startedScroll && lastX - ev.getX() < 0) {
                        if (pager.beginFakeDrag()) {
                            startedScroll = true;
                            lastTranslateX = scrollSlidingTabStrip.getTranslationX();
                        }
                    } else if (startedScroll && lastX - ev.getX() > 0) {
                        if (pager.isFakeDragging()) {
                            pager.endFakeDrag();
                            startedScroll = false;
                        }
                    }
                }
                if (startedScroll) {
                    int dx = (int) (ev.getX() - lastX + newTranslationX - lastTranslateX);
                    try {
                        pager.fakeDragBy(dx);
                        lastTranslateX = newTranslationX;
                    } catch (Exception e) {
                        try {
                            pager.endFakeDrag();
                        } catch (Exception e2) {
                            //don't promt
                        }
                        startedScroll = false;
                        FileLog.e("messenger", e);
                    }
                }
                lastX = ev.getX();
                if (ev.getAction() == MotionEvent.ACTION_CANCEL || ev.getAction() == MotionEvent.ACTION_UP) {
                    first = true;
                    if (startedScroll) {
                        pager.endFakeDrag();
                        startedScroll = false;
                    }
                }
                return startedScroll || super.onTouchEvent(ev);
            }
        };
        scrollSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
        scrollSlidingTabStrip.setIndicatorColor(0xffe2e5e7);
        scrollSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
        scrollSlidingTabStrip.setVisibility(INVISIBLE);
        addView(scrollSlidingTabStrip,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.LEFT | Gravity.TOP));
        scrollSlidingTabStrip.setTranslationX(AndroidUtilities.displaySize.x);
        updateStickerTabs();
        scrollSlidingTabStrip.setDelegate(new ScrollSlidingTabStrip.ScrollSlidingTabStripDelegate() {
            @Override
            public void onPageSelected(int page) {
                if (gifsGridView != null) {
                    if (page == gifTabBum + 1) {
                        if (gifsGridView.getVisibility() != VISIBLE) {
                            listener.onGifTab(true);
                            showGifTab();
                        }
                    } else {
                        if (gifsGridView.getVisibility() == VISIBLE) {
                            listener.onGifTab(false);
                            gifsGridView.setVisibility(GONE);
                            stickersGridView.setVisibility(VISIBLE);
                            stickersEmptyView
                                    .setVisibility(stickersGridAdapter.getCount() != 0 ? GONE : VISIBLE);
                        }
                    }
                }
                if (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else {
                    if (page == gifTabBum + 1) {
                        return;
                    } else {
                        if (page == recentTabBum + 1) {
                            views.get(6).setSelection(0);
                            return;
                        }
                    }
                }
                int index = page - 1 - stickersTabOffset;
                if (index == stickerSets.size()) {
                    if (listener != null) {
                        listener.onStickersSettingsClick();
                    }
                    return;
                }
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
            }
        });

        stickersGridView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                checkStickersScroll(firstVisibleItem);
            }
        });
    }

    setBackgroundColor(0xfff5f6f7);

    pager = new ViewPager(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pager.setAdapter(new EmojiPagesAdapter());

    pagerSlidingTabStripContainer = new LinearLayout(context) {
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            if (getParent() != null) {
                getParent().requestDisallowInterceptTouchEvent(true);
            }
            return super.onInterceptTouchEvent(ev);
        }
    };
    pagerSlidingTabStripContainer.setOrientation(LinearLayout.HORIZONTAL);
    pagerSlidingTabStripContainer.setBackgroundColor(0xfff5f6f7);
    addView(pagerSlidingTabStripContainer, LayoutHelper.createFrame(LayoutParams.MATCH_PARENT, 48));

    PagerSlidingTabStrip pagerSlidingTabStrip = new PagerSlidingTabStrip(context);
    pagerSlidingTabStrip.setViewPager(pager);
    pagerSlidingTabStrip.setShouldExpand(true);
    pagerSlidingTabStrip.setIndicatorHeight(AndroidUtilities.dp(2));
    pagerSlidingTabStrip.setUnderlineHeight(AndroidUtilities.dp(1));
    pagerSlidingTabStrip.setIndicatorColor(0xff2b96e2);
    pagerSlidingTabStrip.setUnderlineColor(0xffe2e5e7);
    pagerSlidingTabStripContainer.addView(pagerSlidingTabStrip, LayoutHelper.createLinear(0, 48, 1.0f));
    pagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            EmojiView.this.onPageScrolled(position, getMeasuredWidth(), positionOffsetPixels);
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

    FrameLayout frameLayout = new FrameLayout(context);
    pagerSlidingTabStripContainer.addView(frameLayout, LayoutHelper.createLinear(52, 48));

    backspaceButton = new ImageView(context) {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                backspacePressed = true;
                backspaceOnce = false;
                postBackspaceRunnable(350);
            } else if (event.getAction() == MotionEvent.ACTION_CANCEL
                    || event.getAction() == MotionEvent.ACTION_UP) {
                backspacePressed = false;
                if (!backspaceOnce) {
                    if (listener != null && listener.onBackspace()) {
                        backspaceButton.performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
                    }
                }
            }
            super.onTouchEvent(event);
            return true;
        }
    };
    backspaceButton.setImageResource(R.drawable.ic_smiles_backspace);
    backspaceButton.setBackgroundResource(R.drawable.ic_emoji_backspace);
    backspaceButton.setScaleType(ImageView.ScaleType.CENTER);
    frameLayout.addView(backspaceButton, LayoutHelper.createFrame(52, 48));

    View view = new View(context);
    view.setBackgroundColor(0xffe2e5e7);
    frameLayout.addView(view, LayoutHelper.createFrame(52, 1, Gravity.LEFT | Gravity.BOTTOM));

    recentsWrap = new FrameLayout(context);
    recentsWrap.addView(views.get(0));

    TextView textView = new TextView(context);
    textView.setText(LocaleController.getString("NoRecent", R.string.NoRecent));
    textView.setTextSize(18);
    textView.setTextColor(0xff888888);
    textView.setGravity(Gravity.CENTER);
    recentsWrap.addView(textView);
    views.get(0).setEmptyView(textView);

    addView(pager, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.LEFT | Gravity.TOP, 0, 48, 0, 0));

    emojiSize = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 40 : 32);
    pickerView = new EmojiColorPickerView(context);
    pickerViewPopup = new EmojiPopupWindow(pickerView,
            popupWidth = AndroidUtilities.dp((AndroidUtilities.isTablet() ? 40 : 32) * 6 + 10 + 4 * 5),
            popupHeight = AndroidUtilities.dp(AndroidUtilities.isTablet() ? 64 : 56));
    pickerViewPopup.setOutsideTouchable(true);
    pickerViewPopup.setClippingEnabled(true);
    pickerViewPopup.setInputMethodMode(EmojiPopupWindow.INPUT_METHOD_NOT_NEEDED);
    pickerViewPopup.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED);
    pickerViewPopup.getContentView().setFocusableInTouchMode(true);
    pickerViewPopup.getContentView().setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0
                    && event.getAction() == KeyEvent.ACTION_UP && pickerViewPopup != null
                    && pickerViewPopup.isShowing()) {
                pickerViewPopup.dismiss();
                return true;
            }
            return false;
        }
    });

    loadRecents();
}

From source file:org.telegram.ui.ProfileActivity.java

@Override
public View createView(Context context) {
    hasOwnBackground = true;/*  w  w  w  .  ja  v a2  s  .  c om*/
    extraHeight = AndroidUtilities.dp(88);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(final int id) {
            if (getParentActivity() == null) {
                return;
            }
            if (id == -1) {
                finishFragment();
            } else if (id == block_contact) {
                TLRPC.User user = MessagesController.getInstance().getUser(user_id);
                if (user == null) {
                    return;
                }
                if (!user.bot) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    if (!userBlocked) {
                        builder.setMessage(LocaleController.getString("AreYouSureBlockContact",
                                R.string.AreYouSureBlockContact));
                    } else {
                        builder.setMessage(LocaleController.getString("AreYouSureUnblockContact",
                                R.string.AreYouSureUnblockContact));
                    }
                    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 (!userBlocked) {
                                        MessagesController.getInstance().blockUser(user_id);
                                    } else {
                                        MessagesController.getInstance().unblockUser(user_id);
                                    }
                                }
                            });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    if (!userBlocked) {
                        MessagesController.getInstance().blockUser(user_id);
                    } else {
                        MessagesController.getInstance().unblockUser(user_id);
                        SendMessagesHelper.getInstance().sendMessage("/start", user_id, null, null, false, null,
                                null, null);
                        finishFragment();
                    }
                }
            } else if (id == add_contact) {
                TLRPC.User user = MessagesController.getInstance().getUser(user_id);
                Bundle args = new Bundle();
                args.putInt("user_id", user.id);
                args.putBoolean("addContact", true);
                presentFragment(new ContactAddActivity(args));
            } else if (id == share_contact) {
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 1);
                args.putString("selectAlertString",
                        LocaleController.getString("SendContactTo", R.string.SendContactTo));
                args.putString("selectAlertStringGroup",
                        LocaleController.getString("SendContactToGroup", R.string.SendContactToGroup));
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(ProfileActivity.this);
                presentFragment(fragment);
            } else if (id == edit_contact) {
                Bundle args = new Bundle();
                args.putInt("user_id", user_id);
                presentFragment(new ContactAddActivity(args));
            } else if (id == delete_contact) {
                final TLRPC.User user = MessagesController.getInstance().getUser(user_id);
                if (user == null || getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(LocaleController.getString("AreYouSureDeleteContact",
                        R.string.AreYouSureDeleteContact));
                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) {
                                ArrayList<TLRPC.User> arrayList = new ArrayList<>();
                                arrayList.add(user);
                                ContactsController.getInstance().deleteContact(arrayList);
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (id == leave_group) {
                leaveChatPressed();
            } else if (id == edit_name) {
                Bundle args = new Bundle();
                args.putInt("chat_id", chat_id);
                presentFragment(new ChangeChatNameActivity(args));
            } else if (id == edit_channel) {
                Bundle args = new Bundle();
                args.putInt("chat_id", chat_id);
                ChannelEditActivity fragment = new ChannelEditActivity(args);
                fragment.setInfo(info);
                presentFragment(fragment);
            } else if (id == invite_to_group) {
                final TLRPC.User user = MessagesController.getInstance().getUser(user_id);
                if (user == null) {
                    return;
                }
                Bundle args = new Bundle();
                args.putBoolean("onlySelect", true);
                args.putInt("dialogsType", 2);
                args.putString("addToGroupAlertString", LocaleController.formatString("AddToTheGroupTitle",
                        R.string.AddToTheGroupTitle, UserObject.getUserName(user), "%1$s"));
                DialogsActivity fragment = new DialogsActivity(args);
                fragment.setDelegate(new DialogsActivity.DialogsActivityDelegate() {
                    @Override
                    public void didSelectDialog(DialogsActivity fragment, long did, boolean param) {
                        Bundle args = new Bundle();
                        args.putBoolean("scrollToTopOnResume", true);
                        args.putInt("chat_id", -(int) did);
                        if (!MessagesController.checkCanOpenChat(args, fragment)) {
                            return;
                        }

                        NotificationCenter.getInstance().removeObserver(ProfileActivity.this,
                                NotificationCenter.closeChats);
                        NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
                        MessagesController.getInstance().addUserToChat(-(int) did, user, null, 0, null,
                                ProfileActivity.this);
                        presentFragment(new ChatActivity(args), true);
                        removeSelfFromStack();
                    }
                });
                presentFragment(fragment);
            } else if (id == share) {
                try {
                    TLRPC.User user = MessagesController.getInstance().getUser(user_id);
                    if (user == null) {
                        return;
                    }
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    String about = MessagesController.getInstance().getUserAbout(botInfo.user_id);
                    if (botInfo != null && about != null) {
                        intent.putExtra(Intent.EXTRA_TEXT,
                                String.format("%s https://telegram.me/%s", about, user.username));
                    } else {
                        intent.putExtra(Intent.EXTRA_TEXT,
                                String.format("https://telegram.me/%s", user.username));
                    }
                    startActivityForResult(Intent.createChooser(intent,
                            LocaleController.getString("BotShare", R.string.BotShare)), 500);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            } else if (id == set_admins) {
                Bundle args = new Bundle();
                args.putInt("chat_id", chat_id);
                SetAdminsActivity fragment = new SetAdminsActivity(args);
                fragment.setChatInfo(info);
                presentFragment(fragment);
            } else if (id == convert_to_supergroup) {
                Bundle args = new Bundle();
                args.putInt("chat_id", chat_id);
                presentFragment(new ConvertGroupActivity(args));
            } else if (id == add_shortcut) {
                try {
                    long did;
                    if (currentEncryptedChat != null) {
                        did = ((long) currentEncryptedChat.id) << 32;
                    } else if (user_id != 0) {
                        did = user_id;
                    } else if (chat_id != 0) {
                        did = -chat_id;
                    } else {
                        return;
                    }
                    AndroidUtilities.installShortcut(did);
                    /*try {
                    Toast.makeText(getParentActivity(), LocaleController.getString("ShortcutAdded", R.string.ShortcutAdded), Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                    FileLog.e("tmessages", e);
                    }*/
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            }
        }
    });

    createActionBarMenu();

    listAdapter = new ListAdapter(context);
    avatarDrawable = new AvatarDrawable();
    avatarDrawable.setProfile(true);

    fragmentView = new FrameLayout(context) {
        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }

        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            checkListViewScroll();
        }
    };
    FrameLayout frameLayout = (FrameLayout) fragmentView;

    listView = new RecyclerListView(context) {
        @Override
        public boolean hasOverlappingRendering() {
            return false;
        }
    };
    listView.setTag(6);
    listView.setPadding(0, AndroidUtilities.dp(88), 0, 0);
    listView.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));
    listView.setVerticalScrollBarEnabled(false);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    listView.setClipToPadding(false);
    layoutManager = new LinearLayoutManager(context) {
        @Override
        public boolean supportsPredictiveItemAnimations() {
            return false;
        }
    };
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    listView.setLayoutManager(layoutManager);
    listView.setGlowColor(AvatarDrawable.getProfileBackColorForId(
            user_id != 0 || ChatObject.isChannel(chat_id) && !currentChat.megagroup ? 5 : chat_id));
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.TOP | Gravity.LEFT));

    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, final int position) {
            if (getParentActivity() == null) {
                return;
            }
            if (position == sharedMediaRow) {
                Bundle args = new Bundle();
                if (user_id != 0) {
                    args.putLong("dialog_id", dialog_id != 0 ? dialog_id : user_id);
                } else {
                    args.putLong("dialog_id", -chat_id);
                }
                MediaActivity fragment = new MediaActivity(args);
                fragment.setChatInfo(info);
                presentFragment(fragment);
            } else if (position == settingsKeyRow) {
                Bundle args = new Bundle();
                args.putInt("chat_id", (int) (dialog_id >> 32));
                presentFragment(new IdenticonActivity(args));
            } else if (position == settingsTimerRow) {
                showDialog(AndroidUtilities.buildTTLAlert(getParentActivity(), currentEncryptedChat).create());
            } else if (position == settingsNotificationsRow) {
                Bundle args = new Bundle();
                if (user_id != 0) {
                    args.putLong("dialog_id", dialog_id == 0 ? user_id : dialog_id);
                } else if (chat_id != 0) {
                    args.putLong("dialog_id", -chat_id);
                }
                presentFragment(new ProfileNotificationsActivity(args));
            } else if (position == startSecretChatRow) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(
                        LocaleController.getString("AreYouSureSecretChat", R.string.AreYouSureSecretChat));
                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) {
                                creatingChat = true;
                                SecretChatHelper.getInstance().startSecretChat(getParentActivity(),
                                        MessagesController.getInstance().getUser(user_id));
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else if (position > emptyRowChat2 && position < membersEndRow) {
                int user_id;
                if (!sortedUsers.isEmpty()) {
                    user_id = info.participants.participants
                            .get(sortedUsers.get(position - emptyRowChat2 - 1)).user_id;
                } else {
                    user_id = info.participants.participants.get(position - emptyRowChat2 - 1).user_id;
                }
                if (user_id == UserConfig.getClientUserId()) {
                    return;
                }
                Bundle args = new Bundle();
                args.putInt("user_id", user_id);
                presentFragment(new ProfileActivity(args));
            } else if (position == addMemberRow) {
                openAddMember();
            } else if (position == channelNameRow) {
                try {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    if (info.about != null && info.about.length() > 0) {
                        intent.putExtra(Intent.EXTRA_TEXT, currentChat.title + "\n" + info.about
                                + "\nhttps://telegram.me/" + currentChat.username);
                    } else {
                        intent.putExtra(Intent.EXTRA_TEXT,
                                currentChat.title + "\nhttps://telegram.me/" + currentChat.username);
                    }
                    getParentActivity().startActivityForResult(Intent.createChooser(intent,
                            LocaleController.getString("BotShare", R.string.BotShare)), 500);
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            } else if (position == leaveChannelRow) {
                leaveChatPressed();
            } else if (position == membersRow || position == blockedUsersRow || position == managementRow) {
                Bundle args = new Bundle();
                args.putInt("chat_id", chat_id);
                if (position == blockedUsersRow) {
                    args.putInt("type", 0);
                } else if (position == managementRow) {
                    args.putInt("type", 1);
                } else if (position == membersRow) {
                    args.putInt("type", 2);
                }
                presentFragment(new ChannelUsersActivity(args));
            } else if (position == convertRow) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setMessage(LocaleController.getString("ConvertGroupAlert", R.string.ConvertGroupAlert));
                builder.setTitle(LocaleController.getString("ConvertGroupAlertWarning",
                        R.string.ConvertGroupAlertWarning));
                builder.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                MessagesController.getInstance().convertToMegaGroup(getParentActivity(),
                                        chat_id);
                            }
                        });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
            } else {
                processOnClickOrPress(position);
            }
        }
    });

    listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {
        @Override
        public boolean onItemClick(View view, int position) {
            if (position > emptyRowChat2 && position < membersEndRow) {
                if (getParentActivity() == null) {
                    return false;
                }
                boolean allowKick = false;
                boolean allowSetAdmin = false;

                final TLRPC.ChatParticipant user;
                if (!sortedUsers.isEmpty()) {
                    user = info.participants.participants.get(sortedUsers.get(position - emptyRowChat2 - 1));
                } else {
                    user = info.participants.participants.get(position - emptyRowChat2 - 1);
                }
                selectedUser = user.user_id;

                if (ChatObject.isChannel(currentChat)) {
                    TLRPC.ChannelParticipant channelParticipant = ((TLRPC.TL_chatChannelParticipant) user).channelParticipant;
                    if (user.user_id != UserConfig.getClientUserId()) {
                        if (currentChat.creator) {
                            allowKick = true;
                        } else if (channelParticipant instanceof TLRPC.TL_channelParticipant) {
                            if (currentChat.editor
                                    || channelParticipant.inviter_id == UserConfig.getClientUserId()) {
                                allowKick = true;
                            }
                        }
                    }
                    TLRPC.User u = MessagesController.getInstance().getUser(user.user_id);
                    allowSetAdmin = channelParticipant instanceof TLRPC.TL_channelParticipant && !u.bot;
                } else {
                    if (user.user_id != UserConfig.getClientUserId()) {
                        if (currentChat.creator) {
                            allowKick = true;
                        } else if (user instanceof TLRPC.TL_chatParticipant) {
                            if (currentChat.admin && currentChat.admins_enabled
                                    || user.inviter_id == UserConfig.getClientUserId()) {
                                allowKick = true;
                            }
                        }
                    }
                }
                if (!allowKick) {
                    return false;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                if (currentChat.megagroup && currentChat.creator && allowSetAdmin) {
                    CharSequence[] items = new CharSequence[] {
                            LocaleController.getString("SetAsAdmin", R.string.SetAsAdmin),
                            LocaleController.getString("KickFromGroup", R.string.KickFromGroup) };
                    builder.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (i == 0) {
                                TLRPC.TL_chatChannelParticipant channelParticipant = ((TLRPC.TL_chatChannelParticipant) user);

                                channelParticipant.channelParticipant = new TLRPC.TL_channelParticipantEditor();
                                channelParticipant.channelParticipant.inviter_id = UserConfig.getClientUserId();
                                channelParticipant.channelParticipant.user_id = user.user_id;
                                channelParticipant.channelParticipant.date = user.date;

                                TLRPC.TL_channels_editAdmin req = new TLRPC.TL_channels_editAdmin();
                                req.channel = MessagesController.getInputChannel(chat_id);
                                req.user_id = MessagesController.getInputUser(selectedUser);
                                req.role = new TLRPC.TL_channelRoleEditor();
                                ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                                    @Override
                                    public void run(TLObject response, final TLRPC.TL_error error) {
                                        if (error == null) {
                                            MessagesController.getInstance()
                                                    .processUpdates((TLRPC.Updates) response, false);
                                            AndroidUtilities.runOnUIThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    MessagesController.getInstance().loadFullChat(chat_id, 0,
                                                            true);
                                                }
                                            }, 1000);
                                        } else {
                                            AndroidUtilities.runOnUIThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    AlertsCreator.showAddUserAlert(error.text,
                                                            ProfileActivity.this, false);
                                                }
                                            });
                                        }
                                    }
                                });
                            } else if (i == 1) {
                                kickUser(selectedUser);
                            }
                        }
                    });
                } else {
                    CharSequence[] items = new CharSequence[] { chat_id > 0
                            ? LocaleController.getString("KickFromGroup", R.string.KickFromGroup)
                            : LocaleController.getString("KickFromBroadcast", R.string.KickFromBroadcast) };
                    builder.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (i == 0) {
                                kickUser(selectedUser);
                            }
                        }
                    });
                }
                showDialog(builder.create());
                return true;
            } else {
                return processOnClickOrPress(position);
            }
        }
    });

    topView = new TopView(context);
    topView.setBackgroundColor(AvatarDrawable.getProfileBackColorForId(
            user_id != 0 || ChatObject.isChannel(chat_id) && !currentChat.megagroup ? 5 : chat_id));
    frameLayout.addView(topView);

    frameLayout.addView(actionBar);

    avatarImage = new BackupImageView(context);
    avatarImage.setRoundRadius(AndroidUtilities.dp(21));
    avatarImage.setPivotX(0);
    avatarImage.setPivotY(0);
    frameLayout.addView(avatarImage, LayoutHelper.createFrame(42, 42, Gravity.TOP | Gravity.LEFT, 64, 0, 0, 0));
    avatarImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (user_id != 0) {
                TLRPC.User user = MessagesController.getInstance().getUser(user_id);
                if (user.photo != null && user.photo.photo_big != null) {
                    PhotoViewer.getInstance().setParentActivity(getParentActivity());
                    PhotoViewer.getInstance().openPhoto(user.photo.photo_big, ProfileActivity.this);
                }
            } else if (chat_id != 0) {
                TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id);
                if (chat.photo != null && chat.photo.photo_big != null) {
                    PhotoViewer.getInstance().setParentActivity(getParentActivity());
                    PhotoViewer.getInstance().openPhoto(chat.photo.photo_big, ProfileActivity.this);
                }
            }
        }
    });

    for (int a = 0; a < 2; a++) {
        if (!playProfileAnimation && a == 0) {
            continue;
        }
        nameTextView[a] = new AutoMarqueeTextView(context);
        nameTextView[a].setTextColor(0xffffffff);
        nameTextView[a].setTextSize(18);
        nameTextView[a].setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
        nameTextView[a].setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
        nameTextView[a].setCompoundDrawablePadding(-AndroidUtilities.dp(1.3f));
        nameTextView[a].setMaxLines(1);
        /*nameTextView[a].setLeftDrawableTopPadding(-AndroidUtilities.dp(1.3f));
        nameTextView[a].setRightDrawableTopPadding(-AndroidUtilities.dp(1.3f));*/
        nameTextView[a].setPivotX(0);
        nameTextView[a].setPivotY(0);
        frameLayout.addView(nameTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, a == 0 ? 48 : 0, 0));

        onlineTextView[a] = new SimpleTextView(context);
        onlineTextView[a].setTextColor(AvatarDrawable.getProfileTextColorForId(
                user_id != 0 || ChatObject.isChannel(chat_id) && !currentChat.megagroup ? 5 : chat_id));
        onlineTextView[a].setTextSize(14);
        onlineTextView[a].setGravity(Gravity.LEFT);
        frameLayout.addView(onlineTextView[a], LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 118, 0, a == 0 ? 48 : 8, 0));
    }

    if (user_id != 0 || chat_id >= 0 && !ChatObject.isLeftFromChat(currentChat)) {
        writeButton = new ImageView(context);
        try {
            writeButton.setBackgroundResource(R.drawable.floating_user_states);
        } catch (Throwable e) {
            FileLog.e("tmessages", e);
        }
        writeButton.setScaleType(ImageView.ScaleType.CENTER);
        if (user_id != 0) {
            writeButton.setImageResource(R.drawable.floating_message);
            writeButton.setPadding(0, AndroidUtilities.dp(3), 0, 0);
        } else if (chat_id != 0) {
            boolean isChannel = ChatObject.isChannel(currentChat);
            if (isChannel && !currentChat.creator && (!currentChat.megagroup || !currentChat.editor)
                    || !isChannel && !currentChat.admin && !currentChat.creator && currentChat.admins_enabled) {
                writeButton.setImageResource(R.drawable.floating_message);
                writeButton.setPadding(0, AndroidUtilities.dp(3), 0, 0);
            } else {
                writeButton.setImageResource(R.drawable.floating_camera);
            }
        }
        frameLayout.addView(writeButton, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT,
                LayoutHelper.WRAP_CONTENT, Gravity.RIGHT | Gravity.TOP, 0, 0, 16, 0));
        if (Build.VERSION.SDK_INT >= 21) {
            StateListAnimator animator = new StateListAnimator();
            animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator
                    .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4))
                    .setDuration(200));
            animator.addState(new int[] {}, ObjectAnimator
                    .ofFloat(writeButton, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2))
                    .setDuration(200));
            writeButton.setStateListAnimator(animator);
            writeButton.setOutlineProvider(new ViewOutlineProvider() {
                @SuppressLint("NewApi")
                @Override
                public void getOutline(View view, Outline outline) {
                    outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
                }
            });
        }
        writeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getParentActivity() == null) {
                    return;
                }
                if (user_id != 0) {
                    if (playProfileAnimation && parentLayout.fragmentsStack
                            .get(parentLayout.fragmentsStack.size() - 2) instanceof ChatActivity) {
                        finishFragment();
                    } else {
                        TLRPC.User user = MessagesController.getInstance().getUser(user_id);
                        if (user == null || user instanceof TLRPC.TL_userEmpty) {
                            return;
                        }
                        Bundle args = new Bundle();
                        args.putInt("user_id", user_id);
                        if (!MessagesController.checkCanOpenChat(args, ProfileActivity.this)) {
                            return;
                        }
                        NotificationCenter.getInstance().removeObserver(ProfileActivity.this,
                                NotificationCenter.closeChats);
                        NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
                        presentFragment(new ChatActivity(args), true);
                    }
                } else if (chat_id != 0) {
                    boolean isChannel = ChatObject.isChannel(currentChat);
                    if (isChannel && !currentChat.creator && (!currentChat.megagroup || !currentChat.editor)
                            || !isChannel && !currentChat.admin && !currentChat.creator
                                    && currentChat.admins_enabled) {
                        if (playProfileAnimation && parentLayout.fragmentsStack
                                .get(parentLayout.fragmentsStack.size() - 2) instanceof ChatActivity) {
                            finishFragment();
                        } else {
                            Bundle args = new Bundle();
                            args.putInt("chat_id", currentChat.id);
                            if (!MessagesController.checkCanOpenChat(args, ProfileActivity.this)) {
                                return;
                            }
                            NotificationCenter.getInstance().removeObserver(ProfileActivity.this,
                                    NotificationCenter.closeChats);
                            NotificationCenter.getInstance()
                                    .postNotificationName(NotificationCenter.closeChats);
                            presentFragment(new ChatActivity(args), true);
                        }
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                        CharSequence[] items;
                        TLRPC.Chat chat = MessagesController.getInstance().getChat(chat_id);
                        if (chat.photo == null || chat.photo.photo_big == null
                                || chat.photo instanceof TLRPC.TL_chatPhotoEmpty) {
                            items = new CharSequence[] {
                                    LocaleController.getString("FromCamera", R.string.FromCamera),
                                    LocaleController.getString("FromGalley", R.string.FromGalley) };
                        } else {
                            items = new CharSequence[] {
                                    LocaleController.getString("FromCamera", R.string.FromCamera),
                                    LocaleController.getString("FromGalley", R.string.FromGalley),
                                    LocaleController.getString("DeletePhoto", R.string.DeletePhoto) };
                        }

                        builder.setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (i == 0) {
                                    avatarUpdater.openCamera();
                                } else if (i == 1) {
                                    avatarUpdater.openGallery();
                                } else if (i == 2) {
                                    MessagesController.getInstance().changeChatAvatar(chat_id, null);
                                }
                            }
                        });
                        showDialog(builder.create());
                    }
                }
            }
        });
    }
    needLayout();

    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            checkListViewScroll();
            if (participantsMap != null && loadMoreMembersRow != -1
                    && layoutManager.findLastVisibleItemPosition() > loadMoreMembersRow - 8) {
                getChannelParticipants(false);
            }
        }
    });

    return fragmentView;
}