Example usage for android.widget FrameLayout addView

List of usage examples for android.widget FrameLayout addView

Introduction

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

Prototype

public void addView(View child, int index) 

Source Link

Document

Adds a child view.

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);
    }//  w ww.ja v a2 s. co m
    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:org.telegram.ui.SettingsActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    actionBar.setItemsBackgroundColor(Theme.getColor(Theme.key_avatar_actionBarSelectorBlue), false);
    actionBar.setItemsColor(Theme.getColor(Theme.key_avatar_actionBarIconBlue), false);
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAddToContainer(false);/* www .jav  a2s  . c  om*/
    extraHeight = 88;
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == edit_name) {
                presentFragment(new ChangeNameActivity());
            } else if (id == logout) {
                presentFragment(new LogoutActivity());
            }
        }
    });
    ActionBarMenu menu = actionBar.createMenu();
    ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
    item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName));
    item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut));

    int scrollTo;
    int scrollToPosition = 0;
    Object writeButtonTag = null;
    if (listView != null) {
        scrollTo = layoutManager.findFirstVisibleItemPosition();
        View topView = layoutManager.findViewByPosition(scrollTo);
        if (topView != null) {
            scrollToPosition = topView.getTop();
        } else {
            scrollTo = -1;
        }
        writeButtonTag = writeButton.getTag();
    } else {
        scrollTo = -1;
    }

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context) {
        @Override
        protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) {
            if (child == listView) {
                boolean result = super.drawChild(canvas, child, drawingTime);
                if (parentLayout != null) {
                    int actionBarHeight = 0;
                    int childCount = getChildCount();
                    for (int a = 0; a < childCount; a++) {
                        View view = getChildAt(a);
                        if (view == child) {
                            continue;
                        }
                        if (view instanceof ActionBar && view.getVisibility() == VISIBLE) {
                            if (((ActionBar) view).getCastShadows()) {
                                actionBarHeight = view.getMeasuredHeight();
                            }
                            break;
                        }
                    }
                    parentLayout.drawHeaderShadow(canvas, actionBarHeight);
                }
                return result;
            } else {
                return super.drawChild(canvas, child, drawingTime);
            }
        }
    };
    fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    FrameLayout frameLayout = (FrameLayout) fragmentView;

    listView = new RecyclerListView(context);
    listView.setVerticalScrollBarEnabled(false);
    listView.setLayoutManager(
            layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {
                @Override
                public boolean supportsPredictiveItemAnimations() {
                    return false;
                }
            });
    listView.setGlowColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
            Gravity.TOP | Gravity.LEFT));
    listView.setAdapter(listAdapter);
    listView.setItemAnimator(null);
    listView.setLayoutAnimation(null);
    listView.setOnItemClickListener((view, position) -> {
        if (position == notificationRow) {
            presentFragment(new NotificationsSettingsActivity());
        } else if (position == privacyRow) {
            presentFragment(new PrivacySettingsActivity());
        } else if (position == dataRow) {
            presentFragment(new DataSettingsActivity());
        } else if (position == chatRow) {
            presentFragment(new ThemeActivity(ThemeActivity.THEME_TYPE_BASIC));
        } else if (position == helpRow) {
            BottomSheet.Builder builder = new BottomSheet.Builder(context);
            builder.setApplyTopPadding(false);

            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.VERTICAL);

            HeaderCell headerCell = new HeaderCell(context, true, 23, 15, false);
            headerCell.setHeight(47);
            headerCell.setText(LocaleController.getString("SettingsHelp", R.string.SettingsHelp));
            linearLayout.addView(headerCell);

            LinearLayout linearLayoutInviteContainer = new LinearLayout(context);
            linearLayoutInviteContainer.setOrientation(LinearLayout.VERTICAL);
            linearLayout.addView(linearLayoutInviteContainer,
                    LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

            int count = 6;
            for (int a = 0; a < count; a++) {
                if (a >= 3 && a <= 4 && !BuildVars.LOGS_ENABLED || a == 5 && !BuildVars.DEBUG_VERSION) {
                    continue;
                }
                TextCell textCell = new TextCell(context);
                String text;
                switch (a) {
                case 0:
                    text = LocaleController.getString("AskAQuestion", R.string.AskAQuestion);
                    break;
                case 1:
                    text = LocaleController.getString("TelegramFAQ", R.string.TelegramFAQ);
                    break;
                case 2:
                    text = LocaleController.getString("PrivacyPolicy", R.string.PrivacyPolicy);
                    break;
                case 3:
                    text = LocaleController.getString("DebugSendLogs", R.string.DebugSendLogs);
                    break;
                case 4:
                    text = LocaleController.getString("DebugClearLogs", R.string.DebugClearLogs);
                    break;
                case 5:
                default:
                    text = "Switch Backend";
                    break;
                }
                textCell.setText(text,
                        BuildVars.LOGS_ENABLED || BuildVars.DEBUG_VERSION ? a != count - 1 : a != 2);
                textCell.setTag(a);
                textCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
                linearLayoutInviteContainer.addView(textCell,
                        LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                textCell.setOnClickListener(v2 -> {
                    Integer tag = (Integer) v2.getTag();
                    switch (tag) {
                    case 0: {
                        showDialog(AlertsCreator.createSupportAlert(SettingsActivity.this));
                        break;
                    }
                    case 1:
                        Browser.openUrl(getParentActivity(),
                                LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
                        break;
                    case 2:
                        Browser.openUrl(getParentActivity(),
                                LocaleController.getString("PrivacyPolicyUrl", R.string.PrivacyPolicyUrl));
                        break;
                    case 3:
                        sendLogs();
                        break;
                    case 4:
                        FileLog.cleanupLogs();
                        break;
                    case 5: {
                        if (getParentActivity() == null) {
                            return;
                        }
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(getParentActivity());
                        builder1.setMessage(LocaleController.getString("AreYouSure", R.string.AreYouSure));
                        builder1.setTitle(LocaleController.getString("AppName", R.string.AppName));
                        builder1.setPositiveButton(LocaleController.getString("OK", R.string.OK),
                                (dialogInterface, i) -> {
                                    SharedConfig.pushAuthKey = null;
                                    SharedConfig.pushAuthKeyId = null;
                                    SharedConfig.saveConfig();
                                    ConnectionsManager.getInstance(currentAccount).switchBackend();
                                });
                        builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                        showDialog(builder1.create());
                        break;
                    }
                    }
                    builder.getDismissRunnable().run();
                });
            }
            builder.setCustomView(linearLayout);
            showDialog(builder.create());
        } else if (position == languageRow) {
            presentFragment(new LanguageSelectActivity());
        } else if (position == usernameRow) {
            presentFragment(new ChangeUsernameActivity());
        } else if (position == bioRow) {
            if (userInfo != null) {
                presentFragment(new ChangeBioActivity());
            }
        } else if (position == numberRow) {
            presentFragment(new ChangePhoneHelpActivity());
        }
    });

    listView.setOnItemLongClickListener(new RecyclerListView.OnItemLongClickListener() {

        private int pressCount = 0;

        @Override
        public boolean onItemClick(View view, int position) {
            if (position == versionRow) {
                pressCount++;
                if (pressCount >= 2 || BuildVars.DEBUG_PRIVATE_VERSION) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("DebugMenu", R.string.DebugMenu));
                    CharSequence[] items;
                    items = new CharSequence[] {
                            LocaleController.getString("DebugMenuImportContacts",
                                    R.string.DebugMenuImportContacts),
                            LocaleController.getString("DebugMenuReloadContacts",
                                    R.string.DebugMenuReloadContacts),
                            LocaleController.getString("DebugMenuResetContacts",
                                    R.string.DebugMenuResetContacts),
                            LocaleController.getString("DebugMenuResetDialogs", R.string.DebugMenuResetDialogs),
                            BuildVars.LOGS_ENABLED
                                    ? LocaleController.getString("DebugMenuDisableLogs",
                                            R.string.DebugMenuDisableLogs)
                                    : LocaleController.getString("DebugMenuEnableLogs",
                                            R.string.DebugMenuEnableLogs),
                            SharedConfig.inappCamera
                                    ? LocaleController.getString("DebugMenuDisableCamera",
                                            R.string.DebugMenuDisableCamera)
                                    : LocaleController.getString("DebugMenuEnableCamera",
                                            R.string.DebugMenuEnableCamera),
                            LocaleController.getString("DebugMenuClearMediaCache",
                                    R.string.DebugMenuClearMediaCache),
                            LocaleController.getString("DebugMenuCallSettings", R.string.DebugMenuCallSettings),
                            null, BuildVars.DEBUG_PRIVATE_VERSION ? "Check for app updates" : null };
                    builder.setItems(items, (dialog, which) -> {
                        if (which == 0) {
                            UserConfig.getInstance(currentAccount).syncContacts = true;
                            UserConfig.getInstance(currentAccount).saveConfig(false);
                            ContactsController.getInstance(currentAccount).forceImportContacts();
                        } else if (which == 1) {
                            ContactsController.getInstance(currentAccount).loadContacts(false, 0);
                        } else if (which == 2) {
                            ContactsController.getInstance(currentAccount).resetImportedContacts();
                        } else if (which == 3) {
                            MessagesController.getInstance(currentAccount).forceResetDialogs();
                        } else if (which == 4) {
                            BuildVars.LOGS_ENABLED = !BuildVars.LOGS_ENABLED;
                            SharedPreferences sharedPreferences = ApplicationLoader.applicationContext
                                    .getSharedPreferences("systemConfig", Context.MODE_PRIVATE);
                            sharedPreferences.edit().putBoolean("logsEnabled", BuildVars.LOGS_ENABLED).commit();
                        } else if (which == 5) {
                            SharedConfig.toggleInappCamera();
                        } else if (which == 6) {
                            MessagesStorage.getInstance(currentAccount).clearSentMedia();
                            SharedPreferences.Editor editor = MessagesController.getGlobalMainSettings().edit();
                            SharedConfig.setNoSoundHintShowed(false);
                        } else if (which == 7) {
                            VoIPHelper.showCallDebugSettings(getParentActivity());
                        } else if (which == 8) {
                            SharedConfig.toggleRoundCamera16to9();
                        } else if (which == 9) {
                            ((LaunchActivity) getParentActivity()).checkAppUpdate(true);
                        }
                    });
                    builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                } else {
                    try {
                        Toast.makeText(getParentActivity(), "\\_()_/", Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                return true;
            }
            return false;
        }
    });

    frameLayout.addView(actionBar);

    extraHeightView = new View(context);
    extraHeightView.setPivotY(0);
    extraHeightView.setBackgroundColor(Theme.getColor(Theme.key_avatar_backgroundActionBarBlue));
    frameLayout.addView(extraHeightView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 88));

    shadowView = new View(context);
    shadowView.setBackgroundResource(R.drawable.header_shadow);
    frameLayout.addView(shadowView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3));

    avatarContainer = new FrameLayout(context);
    avatarContainer.setPivotX(LocaleController.isRTL ? AndroidUtilities.dp(42) : 0);
    avatarContainer.setPivotY(0);
    frameLayout.addView(avatarContainer,
            LayoutHelper.createFrame(42, 42,
                    Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT),
                    (LocaleController.isRTL ? 0 : 64), 0, (LocaleController.isRTL ? 64 : 0), 0));
    avatarContainer.setOnClickListener(v -> {
        if (avatar != null) {
            return;
        }
        TLRPC.User user = MessagesController.getInstance(currentAccount)
                .getUser(UserConfig.getInstance(currentAccount).getClientUserId());
        if (user != null && user.photo != null && user.photo.photo_big != null) {
            PhotoViewer.getInstance().setParentActivity(getParentActivity());
            PhotoViewer.getInstance().openPhoto(user.photo.photo_big, provider);
        }
    });

    avatarImage = new BackupImageView(context);
    avatarImage.setRoundRadius(AndroidUtilities.dp(21));
    avatarContainer.addView(avatarImage, LayoutHelper.createFrame(42, 42));

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(0x55000000);

    avatarProgressView = new RadialProgressView(context) {
        @Override
        protected void onDraw(Canvas canvas) {
            if (avatarImage != null && avatarImage.getImageReceiver().hasNotThumb()) {
                paint.setAlpha((int) (0x55 * avatarImage.getImageReceiver().getCurrentAlpha()));
                canvas.drawCircle(getMeasuredWidth() / 2, getMeasuredHeight() / 2, AndroidUtilities.dp(21),
                        paint);
            }
            super.onDraw(canvas);
        }
    };
    avatarProgressView.setSize(AndroidUtilities.dp(26));
    avatarProgressView.setProgressColor(0xffffffff);
    avatarContainer.addView(avatarProgressView, LayoutHelper.createFrame(42, 42));

    showAvatarProgress(false, false);

    nameTextView = new TextView(context) {
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            setPivotX(LocaleController.isRTL ? getMeasuredWidth() : 0);
        }
    };
    nameTextView.setTextColor(Theme.getColor(Theme.key_profile_title));
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    nameTextView.setLines(1);
    nameTextView.setMaxLines(1);
    nameTextView.setSingleLine(true);
    nameTextView.setEllipsize(TextUtils.TruncateAt.END);
    nameTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
    nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    nameTextView.setPivotY(0);
    frameLayout.addView(nameTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP,
                    LocaleController.isRTL ? 48 : 118, 0, LocaleController.isRTL ? 118 : 48, 0));

    onlineTextView = new TextView(context);
    onlineTextView.setTextColor(Theme.getColor(Theme.key_avatar_subtitleInProfileBlue));
    onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    onlineTextView.setLines(1);
    onlineTextView.setMaxLines(1);
    onlineTextView.setSingleLine(true);
    onlineTextView.setEllipsize(TextUtils.TruncateAt.END);
    onlineTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
    frameLayout.addView(onlineTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP,
                    LocaleController.isRTL ? 48 : 118, 0, LocaleController.isRTL ? 118 : 48, 0));

    writeButton = new ImageView(context);
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56),
            Theme.getColor(Theme.key_profile_actionBackground),
            Theme.getColor(Theme.key_profile_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow_profile)
                .mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        drawable = combinedDrawable;
    }
    writeButton.setBackgroundDrawable(drawable);
    writeButton.setImageResource(R.drawable.menu_camera_av);
    writeButton.setColorFilter(
            new PorterDuffColorFilter(Theme.getColor(Theme.key_profile_actionIcon), PorterDuff.Mode.MULTIPLY));
    writeButton.setScaleType(ImageView.ScaleType.CENTER);
    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));
            }
        });
    }
    frameLayout.addView(writeButton,
            LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60,
                    Build.VERSION.SDK_INT >= 21 ? 56 : 60,
                    (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP,
                    LocaleController.isRTL ? 16 : 0, 0, LocaleController.isRTL ? 0 : 16, 0));
    writeButton.setOnClickListener(v -> {
        TLRPC.User user = MessagesController.getInstance(currentAccount)
                .getUser(UserConfig.getInstance(currentAccount).getClientUserId());
        if (user == null) {
            user = UserConfig.getInstance(currentAccount).getCurrentUser();
        }
        if (user == null) {
            return;
        }
        imageUpdater.openMenu(
                user.photo != null && user.photo.photo_big != null
                        && !(user.photo instanceof TLRPC.TL_userProfilePhotoEmpty),
                () -> MessagesController.getInstance(currentAccount).deleteUserPhoto(null));
    });

    if (scrollTo != -1) {
        layoutManager.scrollToPositionWithOffset(scrollTo, scrollToPosition);

        if (writeButtonTag != null) {
            writeButton.setTag(0);
            writeButton.setScaleX(0.2f);
            writeButton.setScaleY(0.2f);
            writeButton.setAlpha(0.0f);
            writeButton.setVisibility(View.GONE);
        }
    }

    needLayout();

    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (layoutManager.getItemCount() == 0) {
                return;
            }
            int height = 0;
            View child = recyclerView.getChildAt(0);
            if (child != null) {
                if (layoutManager.findFirstVisibleItemPosition() == 0) {
                    height = AndroidUtilities.dp(88) + (child.getTop() < 0 ? child.getTop() : 0);
                }
                if (extraHeight != height) {
                    extraHeight = height;
                    needLayout();
                }
            }
        }
    });

    return fragmentView;
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

private void addSpaceOrPresent(int width) {
    if (width > 0) {
        mLastObstacle = 0;//  www  .  j  a v  a 2s  .  co  m
        // 1/3 chance of a present.
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width,
                LinearLayout.LayoutParams.MATCH_PARENT);
        if (mRandom.nextInt(3) == 0) {
            // Present!

            // Which one?
            Bitmap bmp = mGiftBoxes[mRandom.nextInt(mGiftBoxes.length)];
            ImageView iv = new ImageView(this);
            iv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            iv.setImageBitmap(bmp);

            // Position the present
            int left = mRandom.nextInt(width / 2) + (width / 4)
                    - ((int) ((float) bmp.getWidth() * mScaleX) / 2);
            int top = mRandom.nextInt(mScreenHeight / 2) + (mScreenHeight / 4)
                    - ((int) ((float) bmp.getHeight() * mScaleY) / 2);

            FrameLayout frame = new FrameLayout(this);
            LayoutParams flp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            frame.addView(iv, flp);
            iv.setTranslationX(left);
            iv.setTranslationY(top);

            mObstacleLayout.addView(frame, lp);
        } else {
            // Space
            View view = new View(this);
            mObstacleLayout.addView(view, lp);
        }
    }
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

private void addFinalPresentRun() {
    // Two spacers at the begining.
    View view = new View(this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mSlotWidth, mScreenHeight);
    mObstacleLayout.addView(view, lp);//from   ww  w .  j a  v a 2  s  .c  o m
    view = new View(this);
    mObstacleLayout.addView(view, lp);

    // All of these presents are 500 points (but only if you're awesome)
    if (mElfState == 0) {
        mRainingPresents = true;
    }

    // SIN wave of presents in the middle
    float center = (float) (mScreenHeight / 2);
    float amplitude = (float) (mScreenHeight / 4);

    int count = (3 * SLOTS_PER_SCREEN) - 4;

    for (int i = 0; i < count; i++) {
        float x = (float) ((mSlotWidth - mGiftBoxes[0].getWidth()) / 2);
        float y = center + (amplitude * (float) Math.sin(2.0 * Math.PI * (double) i / (double) count));
        Bitmap bmp = mGiftBoxes[mRandom.nextInt(mGiftBoxes.length)];
        ImageView iv = new ImageView(this);
        iv.setImageBitmap(bmp);
        iv.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        FrameLayout frame = new FrameLayout(this);
        LayoutParams flp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        frame.addView(iv, flp);
        iv.setTranslationX(x);
        iv.setTranslationY(y);
        mObstacleLayout.addView(frame, lp);
    }

    // Two spacers at the end.
    view = new View(this);
    mObstacleLayout.addView(view, lp);
    view = new View(this);
    mObstacleLayout.addView(view, lp);

    // Account for rounding errors in mSlotWidth
    int extra = ((3 * mScreenWidth) - (3 * SLOTS_PER_SCREEN * mSlotWidth));
    if (extra > 0) {
        // Add filler to ensure sync with background/foreground scrolls!
        lp = new LinearLayout.LayoutParams(extra, LinearLayout.LayoutParams.MATCH_PARENT);
        view = new View(this);
        mObstacleLayout.addView(view, lp);
    }
}

From source file:com.google.android.apps.santatracker.rocketsleigh.RocketSleighActivity.java

private void addFirstScreenPresents() {
    // First 4 slots have no nothing.
    for (int i = 0; i < Math.min(4, SLOTS_PER_SCREEN); i++) {
        View view = new View(this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mSlotWidth, mScreenHeight);
        mObstacleLayout.addView(view, lp);
    }//  www. ja va2 s.  co  m

    // Generate a SIN like pattern;
    float center = (float) ((mScreenHeight - mGiftBoxes[0].getHeight()) / 2);
    float presentHeight = (float) mGiftBoxes[0].getHeight();
    float[] heights = new float[] { center, center - presentHeight, center - (1.5f * presentHeight),
            center - presentHeight, center, center + presentHeight, center + (1.5f * presentHeight),
            center + presentHeight, center };
    // Add presents to the end
    if (SLOTS_PER_SCREEN > 4) {
        for (int i = 0; i < (SLOTS_PER_SCREEN - 4); i++) {
            // Which one?
            Bitmap bmp = mGiftBoxes[mRandom.nextInt(mGiftBoxes.length)];
            ImageView iv = new ImageView(this);
            iv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            iv.setImageBitmap(bmp);

            // Position the present
            float left = (mSlotWidth - bmp.getWidth()) / 2;
            float top = heights[(i % heights.length)];

            FrameLayout frame = new FrameLayout(this);
            LayoutParams flp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
            frame.addView(iv, flp);
            iv.setTranslationX(left);
            iv.setTranslationY(top);

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(mSlotWidth,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            mObstacleLayout.addView(frame, lp);
        }
    }

    // Account for rounding errors in mSlotWidth
    int extra = (mScreenWidth - (SLOTS_PER_SCREEN * mSlotWidth));
    if (extra > 0) {
        // Add filler to ensure sync with background/foreground scrolls!
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(extra,
                LinearLayout.LayoutParams.MATCH_PARENT);
        View view = new View(this);
        mObstacleLayout.addView(view, lp);
    }

    mLastObstacle = 0;
}

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

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

    showStickers = needStickers;/*  w ww .  java 2s .co  m*/

    for (int i = 0; i < Emoji.data.length; 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(Emoji.data[i]);
        gridView.setAdapter(emojiGridAdapter);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);
        adapters.add(emojiGridAdapter);
    }

    if (showStickers) {
        StickersQuery.checkStickers();
        GridView gridView = new GridView(context);
        gridView.setColumnWidth(AndroidUtilities.dp(72));
        gridView.setNumColumns(-1);
        gridView.setPadding(0, AndroidUtilities.dp(4), 0, 0);
        gridView.setClipToPadding(false);
        views.add(gridView);
        stickersGridAdapter = new StickersGridAdapter(context);
        gridView.setAdapter(stickersGridAdapter);
        AndroidUtilities.setListViewEdgeEffectColor(gridView, 0xfff5f6f7);

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

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

        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);
        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 (page == 0) {
                    pager.setCurrentItem(0);
                    return;
                } else if (page == 1 && !recentStickers.isEmpty()) {
                    views.get(6).setSelection(0);
                    return;
                }
                int index = page - (recentStickers.isEmpty() ? 1 : 2);
                if (index >= stickerSets.size()) {
                    index = stickerSets.size() - 1;
                }
                views.get(6).setSelection(stickersGridAdapter.getPositionForPack(stickerSets.get(index)));
            }
        });

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

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                int count = view.getChildCount();
                for (int a = 0; a < count; a++) {
                    View child = view.getChildAt(a);
                    if (child.getHeight() + child.getTop() < AndroidUtilities.dp(5)) {
                        firstVisibleItem++;
                    } else {
                        break;
                    }
                }
                scrollSlidingTabStrip
                        .onPageScrolled(stickersGridAdapter.getTabForPosition(firstVisibleItem) + 1, 0);
            }
        });
    }

    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 (EmojiView.this.listener != null && EmojiView.this.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));

    loadRecents();

    if (Emoji.data[0] == null || Emoji.data[0].length == 0) {
        pager.setCurrentItem(1);
    }
}

From source file:com.waz.zclient.ui.cursor.CursorLayout.java

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    editMessageBackgroundView = ViewUtils.getView(this, R.id.fl__edit_message__background);
    cursorToolbarFrame = ViewUtils.getView(this, R.id.cal__cursor);
    newCursorEditText = ViewUtils.getView(this, R.id.cet__cursor);
    shieldViewWithBanner = ViewUtils.getView(this, R.id.svwb);
    mainToolbar = ViewUtils.getView(this, R.id.c__cursor__main);
    secondaryToolbar = ViewUtils.getView(this, R.id.c__cursor__secondary);
    editMessageCursorToolbar = ViewUtils.getView(this, R.id.emct__edit_message__toolbar);
    topBorder = ViewUtils.getView(this, R.id.v__top_bar__cursor);
    tooltip = ViewUtils.getView(this, R.id.ctv__cursor);
    hintView = ViewUtils.getView(this, R.id.ttv__cursor_hint);
    dividerView = ViewUtils.getView(this, R.id.v__cursor__divider);
    FrameLayout emojiButtonContainer = ViewUtils.getView(this, R.id.fl__cursor__emoji_container);
    FrameLayout sendButtonContainer = ViewUtils.getView(this, R.id.fl__cursor__send_button_container);

    mainToolbar.setCursorItems(mainCursorItems);
    secondaryToolbar.setCursorItems(secondaryCursorItems);
    editMessageCursorToolbar.setVisibility(GONE);
    editMessageCursorToolbar.setCallback(this);

    cursorHeight = getResources().getDimensionPixelSize(R.dimen.new_cursor_height);
    secondaryToolbar.setTranslationY(2 * cursorHeight);
    cursorToolbarAnimationDuration = getResources().getInteger(R.integer.wire__animation__delay__regular);
    tooltip.setVisibility(View.GONE);
    connectEditText();//w  w  w.j  av a2  s.c o  m
    editMessageBackgroundView.setVisibility(GONE);

    defaultEditTextColor = newCursorEditText.getCurrentTextColor();
    ColorDrawable dividerBg = (ColorDrawable) dividerView.getBackground();
    defaultDividerColor = dividerBg.getColor();

    // Emoji button
    LayoutInflater inflater = LayoutInflater.from(getContext());
    emojiButton = (CursorIconButton) inflater.inflate(R.layout.cursor__item, this, false);
    emojiButton.setText(R.string.glyph__emoji);
    emojiButton.setPressedBackgroundColor(ContextCompat.getColor(getContext(), R.color.light_graphite));
    int buttonWidth = getResources().getDimensionPixelSize(R.dimen.cursor__menu_button__diameter);
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(buttonWidth, buttonWidth);
    params.gravity = Gravity.END | Gravity.CENTER_VERTICAL;
    params.setMarginEnd(getResources().getDimensionPixelSize(R.dimen.chathead__margin));
    emojiButtonContainer.addView(emojiButton, params);
    emojiButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (cursorCallback == null) {
                return;
            }
            mainToolbar.unselectItems();
            if (getContext().getString(R.string.glyph__emoji).equals(emojiButton.getText())) {
                emojiButton.setText(R.string.glyph__keyboard);
                cursorCallback.onEmojiButtonClicked(true);
            } else {
                emojiButton.setText(R.string.glyph__emoji);
                cursorCallback.onEmojiButtonClicked(false);
            }
        }
    });

    // Send button
    sendButton = (CursorIconButton) inflater.inflate(R.layout.cursor__item, this, false);
    sendButton.setText(R.string.glyph__send);
    if (!ThemeUtils.isDarkTheme(getContext())) {
        sendButton.setTextColor(ContextCompat.getColor(getContext(), R.color.text__primary_dark));
    } else {
        sendButton.setTextColor(ContextCompat.getColor(getContext(), R.color.text__primary_light));
    }
    sendButtonContainer.addView(sendButton, new FrameLayout.LayoutParams(buttonWidth, buttonWidth));
    sendButton.setVisibility(View.INVISIBLE);
}

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

@Override
public View createView(Context context) {
    searching = false;//from  www .jav a 2  s . c om
    searchWas = false;

    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                if (currentStep == 0) {
                    if (donePressed) {
                        return;
                    }
                    if (nameTextView.length() == 0) {
                        Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                        if (v != null) {
                            v.vibrate(200);
                        }
                        AndroidUtilities.shakeView(nameTextView, 2, 0);
                        return;
                    }
                    donePressed = true;
                    if (avatarUpdater.uploadingAvatar != null) {
                        createAfterUpload = true;
                        progressDialog = new ProgressDialog(getParentActivity());
                        progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
                        progressDialog.setCanceledOnTouchOutside(false);
                        progressDialog.setCancelable(false);
                        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                                LocaleController.getString("Cancel", R.string.Cancel),
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        createAfterUpload = false;
                                        progressDialog = null;
                                        donePressed = false;
                                        try {
                                            dialog.dismiss();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        }
                                    }
                                });
                        progressDialog.show();
                        return;
                    }
                    final int reqId = MessagesController.getInstance().createChat(
                            nameTextView.getText().toString(), new ArrayList<Integer>(),
                            descriptionTextView.getText().toString(), ChatObject.CHAT_TYPE_CHANNEL,
                            ChannelCreateActivity.this);
                    progressDialog = new ProgressDialog(getParentActivity());
                    progressDialog.setMessage(LocaleController.getString("Loading", R.string.Loading));
                    progressDialog.setCanceledOnTouchOutside(false);
                    progressDialog.setCancelable(false);
                    progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE,
                            LocaleController.getString("Cancel", R.string.Cancel),
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    ConnectionsManager.getInstance().cancelRequest(reqId, true);
                                    donePressed = false;
                                    try {
                                        dialog.dismiss();
                                    } catch (Exception e) {
                                        FileLog.e("tmessages", e);
                                    }
                                }
                            });
                    progressDialog.show();
                } else if (currentStep == 1) {
                    if (!isPrivate) {
                        if (nameTextView.length() == 0) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                            builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                            builder.setMessage(LocaleController.getString("ChannelPublicEmptyUsername",
                                    R.string.ChannelPublicEmptyUsername));
                            builder.setPositiveButton(LocaleController.getString("Close", R.string.Close),
                                    null);
                            showDialog(builder.create());
                            return;
                        } else {
                            if (!lastNameAvailable) {
                                Vibrator v = (Vibrator) getParentActivity()
                                        .getSystemService(Context.VIBRATOR_SERVICE);
                                if (v != null) {
                                    v.vibrate(200);
                                }
                                AndroidUtilities.shakeView(checkTextView, 2, 0);
                                return;
                            } else {
                                MessagesController.getInstance().updateChannelUserName(chatId, lastCheckName);
                            }
                        }
                    }
                    Bundle args = new Bundle();
                    args.putInt("step", 2);
                    args.putInt("chat_id", chatId);
                    presentFragment(new ChannelCreateActivity(args), true);
                } else {
                    ArrayList<TLRPC.InputUser> result = new ArrayList<>();
                    for (Integer uid : selectedContacts.keySet()) {
                        TLRPC.InputUser user = MessagesController
                                .getInputUser(MessagesController.getInstance().getUser(uid));
                        if (user != null) {
                            result.add(user);
                        }
                    }
                    MessagesController.getInstance().addUsersToChannel(chatId, result, null);
                    NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeChats);
                    Bundle args2 = new Bundle();
                    args2.putInt("chat_id", chatId);
                    presentFragment(new ChatActivity(args2), true);
                }
            }
        }
    });

    ActionBarMenu menu = actionBar.createMenu();
    doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));

    if (currentStep != 2) {
        fragmentView = new ScrollView(context);
        ScrollView scrollView = (ScrollView) fragmentView;
        scrollView.setFillViewport(true);
        linearLayout = new LinearLayout(context);
        scrollView.addView(linearLayout, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
    } else {
        fragmentView = new LinearLayout(context);
        fragmentView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        linearLayout = (LinearLayout) fragmentView;
    }
    linearLayout.setOrientation(LinearLayout.VERTICAL);

    if (currentStep == 0) {
        actionBar.setTitle(LocaleController.getString("NewChannel", R.string.NewChannel));
        fragmentView.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background));
        FrameLayout frameLayout = new FrameLayout(context);
        linearLayout.addView(frameLayout,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        avatarImage = new BackupImageView(context);
        avatarImage.setRoundRadius(AndroidUtilities.dp(32));
        avatarDrawable.setInfo(5, null, null, false);
        avatarDrawable.setDrawPhoto(true);
        avatarImage.setImageDrawable(avatarDrawable);
        frameLayout.addView(avatarImage,
                LayoutHelper.createFrame(64, 64,
                        Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT),
                        LocaleController.isRTL ? 0 : 16, 12, LocaleController.isRTL ? 16 : 0, 12));
        avatarImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());

                CharSequence[] items;

                if (avatar != null) {
                    items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera),
                            LocaleController.getString("FromGalley", R.string.FromGalley),
                            LocaleController.getString("DeletePhoto", R.string.DeletePhoto) };
                } else {
                    items = new CharSequence[] { LocaleController.getString("FromCamera", R.string.FromCamera),
                            LocaleController.getString("FromGalley", R.string.FromGalley) };
                }

                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) {
                            avatar = null;
                            uploadedAvatar = null;
                            avatarImage.setImage(avatar, "50_50", avatarDrawable);
                        }
                    }
                });
                showDialog(builder.create());
            }
        });

        nameTextView = new EditText(context);
        nameTextView.setHint(LocaleController.getString("EnterChannelName", R.string.EnterChannelName));
        if (nameToSet != null) {
            nameTextView.setText(nameToSet);
            nameToSet = null;
        }
        nameTextView.setMaxLines(4);
        nameTextView
                .setGravity(Gravity.CENTER_VERTICAL | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT));
        nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        //nameTextView.setHintTextColor(0xff979797);
        nameTextView.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        nameTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
        InputFilter[] inputFilters = new InputFilter[1];
        inputFilters[0] = new InputFilter.LengthFilter(100);
        nameTextView.setFilters(inputFilters);
        nameTextView.setPadding(0, 0, 0, AndroidUtilities.dp(8));
        AndroidUtilities.clearCursorDrawable(nameTextView);
        nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
        frameLayout.addView(nameTextView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT,
                        Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 16 : 96, 0,
                        LocaleController.isRTL ? 96 : 16, 0));
        nameTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                avatarDrawable.setInfo(5, nameTextView.length() > 0 ? nameTextView.getText().toString() : null,
                        null, false);
                avatarImage.invalidate();
            }
        });

        descriptionTextView = new EditText(context);
        descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        //descriptionTextView.setHintTextColor(0xff979797);
        descriptionTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
        descriptionTextView.setPadding(0, 0, 0, AndroidUtilities.dp(6));
        descriptionTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
        descriptionTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
                | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
        descriptionTextView.setImeOptions(EditorInfo.IME_ACTION_DONE);
        inputFilters = new InputFilter[1];
        inputFilters[0] = new InputFilter.LengthFilter(120);
        descriptionTextView.setFilters(inputFilters);
        descriptionTextView
                .setHint(LocaleController.getString("DescriptionPlaceholder", R.string.DescriptionPlaceholder));
        AndroidUtilities.clearCursorDrawable(descriptionTextView);
        linearLayout.addView(descriptionTextView,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 24, 18, 24, 0));
        descriptionTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_DONE && doneButton != null) {
                    doneButton.performClick();
                    return true;
                }
                return false;
            }
        });
        descriptionTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

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

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        TextView helpTextView = new TextView(context);
        helpTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
        //helpTextView.setTextColor(0xff6d6d72);
        helpTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
        helpTextView.setText(LocaleController.getString("DescriptionInfo", R.string.DescriptionInfo));
        linearLayout.addView(helpTextView,
                LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                        LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 24, 10, 24, 20));
    } else if (currentStep == 1) {
        actionBar.setTitle(LocaleController.getString("ChannelSettings", R.string.ChannelSettings));
        fragmentView.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));

        LinearLayout linearLayout2 = new LinearLayout(context);
        linearLayout2.setOrientation(LinearLayout.VERTICAL);
        linearLayout2.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background));
        linearLayout2.setElevation(AndroidUtilities.dp(2));
        linearLayout.addView(linearLayout2,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        radioButtonCell1 = new RadioButtonCell(context);
        radioButtonCell1.setElevation(0);
        radioButtonCell1.setForeground(R.drawable.list_selector);
        radioButtonCell1.setTextAndValue(LocaleController.getString("ChannelPublic", R.string.ChannelPublic),
                LocaleController.getString("ChannelPublicInfo", R.string.ChannelPublicInfo), !isPrivate, false);
        linearLayout2.addView(radioButtonCell1,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        radioButtonCell1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isPrivate) {
                    return;
                }
                isPrivate = false;
                updatePrivatePublic();
            }
        });

        radioButtonCell2 = new RadioButtonCell(context);
        radioButtonCell2.setElevation(0);
        radioButtonCell2.setForeground(R.drawable.list_selector);
        radioButtonCell2.setTextAndValue(LocaleController.getString("ChannelPrivate", R.string.ChannelPrivate),
                LocaleController.getString("ChannelPrivateInfo", R.string.ChannelPrivateInfo), isPrivate,
                false);
        linearLayout2.addView(radioButtonCell2,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        radioButtonCell2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPrivate) {
                    return;
                }
                isPrivate = true;
                updatePrivatePublic();
            }
        });

        sectionCell = new ShadowSectionCell(context);
        linearLayout.addView(sectionCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        linkContainer = new LinearLayout(context);
        linkContainer.setOrientation(LinearLayout.VERTICAL);
        linkContainer.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background));
        linkContainer.setElevation(AndroidUtilities.dp(2));
        linearLayout.addView(linkContainer,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        headerCell = new HeaderCell(context);
        linkContainer.addView(headerCell);

        publicContainer = new LinearLayout(context);
        publicContainer.setOrientation(LinearLayout.HORIZONTAL);
        linkContainer.addView(publicContainer,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36, 17, 7, 17, 0));

        EditText editText = new EditText(context);
        editText.setText("telegram.me/");
        editText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        //editText.setHintTextColor(0xff979797);
        editText.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
        editText.setMaxLines(1);
        editText.setLines(1);
        editText.setEnabled(false);
        editText.setBackgroundDrawable(null);
        editText.setPadding(0, 0, 0, 0);
        editText.setSingleLine(true);
        editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
        editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
        publicContainer.addView(editText, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, 36));

        nameTextView = new EditText(context);
        nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
        //nameTextView.setHintTextColor(0xff979797);
        nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
        nameTextView.setMaxLines(1);
        nameTextView.setLines(1);
        nameTextView.setBackgroundDrawable(null);
        nameTextView.setPadding(0, 0, 0, 0);
        nameTextView.setSingleLine(true);
        nameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
                | InputType.TYPE_TEXT_FLAG_MULTI_LINE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT);
        nameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE);
        nameTextView.setHint(
                LocaleController.getString("ChannelUsernamePlaceholder", R.string.ChannelUsernamePlaceholder));
        AndroidUtilities.clearCursorDrawable(nameTextView);
        publicContainer.addView(nameTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 36));
        nameTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                checkUserName(nameTextView.getText().toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        privateContainer = new TextBlockCell(context);
        privateContainer.setForeground(R.drawable.list_selector);
        privateContainer.setElevation(0);
        linkContainer.addView(privateContainer);
        privateContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (invite == null) {
                    return;
                }
                try {
                    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) ApplicationLoader.applicationContext
                            .getSystemService(Context.CLIPBOARD_SERVICE);
                    android.content.ClipData clip = android.content.ClipData.newPlainText("label", invite.link);
                    clipboard.setPrimaryClip(clip);
                    Toast.makeText(getParentActivity(),
                            LocaleController.getString("LinkCopied", R.string.LinkCopied), Toast.LENGTH_SHORT)
                            .show();
                } catch (Exception e) {
                    FileLog.e("tmessages", e);
                }
            }
        });

        checkTextView = new TextView(context);
        checkTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
        checkTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
        checkTextView.setVisibility(View.GONE);
        linkContainer.addView(checkTextView,
                LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                        LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT, 17, 3, 17, 7));

        typeInfoCell = new TextInfoPrivacyCell(context);
        //typeInfoCell.setBackgroundResource(R.drawable.greydivider_bottom);
        linearLayout.addView(typeInfoCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        loadingAdminedCell = new LoadingCell(context);
        linearLayout.addView(loadingAdminedCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        adminedInfoCell = new TextInfoPrivacyCell(context);
        //adminedInfoCell.setBackgroundResource(R.drawable.greydivider_bottom);
        linearLayout.addView(adminedInfoCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        updatePrivatePublic();
    } else if (currentStep == 2) {
        actionBar.setTitle(LocaleController.getString("ChannelAddMembers", R.string.ChannelAddMembers));
        actionBar.setSubtitle(LocaleController.formatPluralString("Members", selectedContacts.size()));

        searchListViewAdapter = new SearchAdapter(context, null, false, false, false, false);
        searchListViewAdapter.setCheckedMap(selectedContacts);
        searchListViewAdapter.setUseUserCell(true);
        listViewAdapter = new ContactsAdapter(context, 1, false, null, false);
        listViewAdapter.setCheckedMap(selectedContacts);

        FrameLayout frameLayout = new FrameLayout(context);
        frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.chat_list_background));

        linearLayout.addView(frameLayout,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        nameTextView = new EditText(context);
        nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        //nameTextView.setHintTextColor(0xff979797);
        nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text));
        nameTextView.setInputType(InputType.TYPE_TEXT_VARIATION_FILTER | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
                | InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        nameTextView.setMinimumHeight(AndroidUtilities.dp(54));
        nameTextView.setSingleLine(false);
        nameTextView.setLines(2);
        nameTextView.setMaxLines(2);
        nameTextView.setVerticalScrollBarEnabled(true);
        nameTextView.setHorizontalScrollBarEnabled(false);
        nameTextView.setPadding(0, 0, 0, 0);
        nameTextView.setHint(LocaleController.getString("AddMutual", R.string.AddMutual));
        nameTextView.setTextIsSelectable(false);
        nameTextView.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        nameTextView
                .setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
        AndroidUtilities.clearCursorDrawable(nameTextView);
        frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
                LayoutHelper.WRAP_CONTENT, Gravity.LEFT | Gravity.TOP, 10, 0, 10, 0));

        nameTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
                if (!ignoreChange) {
                    beforeChangeIndex = nameTextView.getSelectionStart();
                    changeString = new SpannableString(charSequence);
                }
            }

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

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (!ignoreChange) {
                    boolean search = false;
                    int afterChangeIndex = nameTextView.getSelectionEnd();
                    if (editable.toString().length() < changeString.toString().length()) {
                        String deletedString = "";
                        try {
                            deletedString = changeString.toString().substring(afterChangeIndex,
                                    beforeChangeIndex);
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                        if (deletedString.length() > 0) {
                            if (searching && searchWas) {
                                search = true;
                            }
                            Spannable span = nameTextView.getText();
                            for (int a = 0; a < allSpans.size(); a++) {
                                ChipSpan sp = allSpans.get(a);
                                if (span.getSpanStart(sp) == -1) {
                                    allSpans.remove(sp);
                                    selectedContacts.remove(sp.uid);
                                }
                            }
                            actionBar.setSubtitle(
                                    LocaleController.formatPluralString("Members", selectedContacts.size()));
                            listView.invalidateViews();
                        } else {
                            search = true;
                        }
                    } else {
                        search = true;
                    }
                    if (search) {
                        String text = nameTextView.getText().toString().replace("<", "");
                        if (text.length() != 0) {
                            searching = true;
                            searchWas = true;
                            if (listView != null) {
                                listView.setAdapter(searchListViewAdapter);
                                searchListViewAdapter.notifyDataSetChanged();
                                listView.setFastScrollAlwaysVisible(false);
                                listView.setFastScrollEnabled(false);
                                listView.setVerticalScrollBarEnabled(true);
                            }
                            if (emptyTextView != null) {
                                emptyTextView
                                        .setText(LocaleController.getString("NoResult", R.string.NoResult));
                            }
                            searchListViewAdapter.searchDialogs(text);
                        } else {
                            searchListViewAdapter.searchDialogs(null);
                            searching = false;
                            searchWas = false;
                            listView.setAdapter(listViewAdapter);
                            listViewAdapter.notifyDataSetChanged();
                            listView.setFastScrollAlwaysVisible(true);
                            listView.setFastScrollEnabled(true);
                            listView.setVerticalScrollBarEnabled(false);
                            emptyTextView
                                    .setText(LocaleController.getString("NoContacts", R.string.NoContacts));
                        }
                    }
                }
            }
        });

        LinearLayout emptyTextLayout = new LinearLayout(context);
        emptyTextLayout.setVisibility(View.INVISIBLE);
        emptyTextLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(emptyTextLayout,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        emptyTextLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        emptyTextView = new TextView(context);
        emptyTextView.setTextColor(0xff808080);
        emptyTextView.setTextSize(20);
        emptyTextView.setGravity(Gravity.CENTER);
        emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
        emptyTextLayout.addView(emptyTextView,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0.5f));

        FrameLayout frameLayout2 = new FrameLayout(context);
        emptyTextLayout.addView(frameLayout2,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 0.5f));

        listView = new LetterSectionsListView(context);
        listView.setEmptyView(emptyTextLayout);
        listView.setVerticalScrollBarEnabled(false);
        listView.setDivider(null);
        listView.setDividerHeight(0);
        listView.setFastScrollEnabled(true);
        listView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        listView.setAdapter(listViewAdapter);
        listView.setFastScrollAlwaysVisible(true);
        listView.setVerticalScrollbarPosition(
                LocaleController.isRTL ? ListView.SCROLLBAR_POSITION_LEFT : ListView.SCROLLBAR_POSITION_RIGHT);
        linearLayout.addView(listView,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TLRPC.User user;
                if (searching && searchWas) {
                    user = (TLRPC.User) searchListViewAdapter.getItem(i);
                } else {
                    int section = listViewAdapter.getSectionForPosition(i);
                    int row = listViewAdapter.getPositionInSectionForPosition(i);
                    if (row < 0 || section < 0) {
                        return;
                    }
                    user = (TLRPC.User) listViewAdapter.getItem(section, row);
                }
                if (user == null) {
                    return;
                }

                boolean check = true;
                if (selectedContacts.containsKey(user.id)) {
                    check = false;
                    try {
                        ChipSpan span = selectedContacts.get(user.id);
                        selectedContacts.remove(user.id);
                        SpannableStringBuilder text = new SpannableStringBuilder(nameTextView.getText());
                        text.delete(text.getSpanStart(span), text.getSpanEnd(span));
                        allSpans.remove(span);
                        ignoreChange = true;
                        nameTextView.setText(text);
                        nameTextView.setSelection(text.length());
                        ignoreChange = false;
                    } catch (Exception e) {
                        FileLog.e("tmessages", e);
                    }
                } else {
                    ignoreChange = true;
                    ChipSpan span = createAndPutChipForUser(user);
                    if (span != null) {
                        span.uid = user.id;
                    }
                    ignoreChange = false;
                    if (span == null) {
                        return;
                    }
                }
                actionBar.setSubtitle(LocaleController.formatPluralString("Members", selectedContacts.size()));
                if (searching || searchWas) {
                    ignoreChange = true;
                    SpannableStringBuilder ssb = new SpannableStringBuilder("");
                    for (ImageSpan sp : allSpans) {
                        ssb.append("<<");
                        ssb.setSpan(sp, ssb.length() - 2, ssb.length(),
                                SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                    nameTextView.setText(ssb);
                    nameTextView.setSelection(ssb.length());
                    ignoreChange = false;

                    searchListViewAdapter.searchDialogs(null);
                    searching = false;
                    searchWas = false;
                    listView.setAdapter(listViewAdapter);
                    listViewAdapter.notifyDataSetChanged();
                    listView.setFastScrollAlwaysVisible(true);
                    listView.setFastScrollEnabled(true);
                    listView.setVerticalScrollBarEnabled(false);
                    emptyTextView.setText(LocaleController.getString("NoContacts", R.string.NoContacts));
                } else {
                    if (view instanceof UserCell) {
                        ((UserCell) view).setChecked(check, true);
                    }
                }
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (i == SCROLL_STATE_TOUCH_SCROLL) {
                    AndroidUtilities.hideKeyboard(nameTextView);
                }
                if (listViewAdapter != null) {
                    listViewAdapter.setIsScrolling(i != SCROLL_STATE_IDLE);
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                if (absListView.isFastScrollEnabled()) {
                    AndroidUtilities.clearDrawableAnimation(absListView);
                }
            }
        });
    }

    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//from   w ww.  j a  va 2 s  .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:com.dish.browser.activity.BrowserActivity.java

@Override
public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
    if (view == null) {
        return;//from  w w w.j a v  a2 s.co m
    }
    if (mCustomView != null && callback != null) {
        callback.onCustomViewHidden();
        return;
    }
    try {
        view.setKeepScreenOn(true);
    } catch (SecurityException e) {
        Log.e(Constants.TAG, "WebView is not allowed to keep the screen on");
    }
    mOriginalOrientation = getRequestedOrientation();
    FrameLayout decor = (FrameLayout) getWindow().getDecorView();
    mFullscreenContainer = new FullscreenHolder(this);
    mCustomView = view;
    mFullscreenContainer.addView(mCustomView, COVER_SCREEN_PARAMS);
    decor.addView(mFullscreenContainer, COVER_SCREEN_PARAMS);
    setFullscreen(true);
    mCurrentView.setVisibility(View.GONE);
    if (view instanceof FrameLayout) {
        if (((FrameLayout) view).getFocusedChild() instanceof VideoView) {
            mVideoView = (VideoView) ((FrameLayout) view).getFocusedChild();
            mVideoView.setOnErrorListener(new VideoCompletionListener());
            mVideoView.setOnCompletionListener(new VideoCompletionListener());
        }
    }
    mCustomViewCallback = callback;
}