Search in sources :

Example 6 with TextSettingsCell

use of org.telegram.ui.Cells.TextSettingsCell in project Telegram-FOSS by Telegram-FOSS-Team.

the class ThemeActivity method updateSunTime.

private void updateSunTime(Location lastKnownLocation, boolean forceUpdate) {
    LocationManager locationManager = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE);
    if (Build.VERSION.SDK_INT >= 23) {
        Activity activity = getParentActivity();
        if (activity != null) {
            if (activity.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                activity.requestPermissions(new String[] { Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION }, 2);
                return;
            }
        }
    }
    if (getParentActivity() != null) {
        if (!getParentActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)) {
            return;
        }
        try {
            LocationManager lm = (LocationManager) ApplicationLoader.applicationContext.getSystemService(Context.LOCATION_SERVICE);
            if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("GpsDisabledAlertTitle", R.string.GpsDisabledAlertTitle));
                builder.setMessage(LocaleController.getString("GpsDisabledAlertText", R.string.GpsDisabledAlertText));
                builder.setPositiveButton(LocaleController.getString("ConnectingToProxyEnable", R.string.ConnectingToProxyEnable), (dialog, id) -> {
                    if (getParentActivity() == null) {
                        return;
                    }
                    try {
                        getParentActivity().startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    } catch (Exception ignore) {
                    }
                });
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                showDialog(builder.create());
                return;
            }
        } catch (Exception e) {
            FileLog.e(e);
        }
    }
    try {
        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        if (lastKnownLocation == null) {
            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
        }
    } catch (Exception e) {
        FileLog.e(e);
    }
    if (lastKnownLocation == null || forceUpdate) {
        startLocationUpdate();
        if (lastKnownLocation == null) {
            return;
        }
    }
    Theme.autoNightLocationLatitude = lastKnownLocation.getLatitude();
    Theme.autoNightLocationLongitude = lastKnownLocation.getLongitude();
    int[] time = SunDate.calculateSunriseSunset(Theme.autoNightLocationLatitude, Theme.autoNightLocationLongitude);
    Theme.autoNightSunriseTime = time[0];
    Theme.autoNightSunsetTime = time[1];
    Theme.autoNightCityName = null;
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    Theme.autoNightLastSunCheckDay = calendar.get(Calendar.DAY_OF_MONTH);
    Utilities.globalQueue.postRunnable(() -> {
        String name;
        try {
            Geocoder gcd = new Geocoder(ApplicationLoader.applicationContext, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(Theme.autoNightLocationLatitude, Theme.autoNightLocationLongitude, 1);
            if (addresses.size() > 0) {
                name = addresses.get(0).getLocality();
            } else {
                name = null;
            }
        } catch (Exception ignore) {
            name = null;
        }
        final String nameFinal = name;
        AndroidUtilities.runOnUIThread(() -> {
            Theme.autoNightCityName = nameFinal;
            if (Theme.autoNightCityName == null) {
                Theme.autoNightCityName = String.format("(%.06f, %.06f)", Theme.autoNightLocationLatitude, Theme.autoNightLocationLongitude);
            }
            Theme.saveAutoNightThemeConfig();
            if (listView != null) {
                RecyclerListView.Holder holder = (RecyclerListView.Holder) listView.findViewHolderForAdapterPosition(scheduleUpdateLocationRow);
                if (holder != null && holder.itemView instanceof TextSettingsCell) {
                    ((TextSettingsCell) holder.itemView).setTextAndValue(LocaleController.getString("AutoNightUpdateLocation", R.string.AutoNightUpdateLocation), Theme.autoNightCityName, false);
                }
            }
        });
    });
    RecyclerListView.Holder holder = (RecyclerListView.Holder) listView.findViewHolderForAdapterPosition(scheduleLocationInfoRow);
    if (holder != null && holder.itemView instanceof TextInfoPrivacyCell) {
        ((TextInfoPrivacyCell) holder.itemView).setText(getLocationSunString());
    }
    if (Theme.autoNightScheduleByLocation && Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SCHEDULED) {
        Theme.checkAutoNightThemeConditions();
    }
}
Also used : LocationManager(android.location.LocationManager) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Address(android.location.Address) Calendar(java.util.Calendar) Activity(android.app.Activity) Intent(android.content.Intent) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) RecyclerListView(org.telegram.ui.Components.RecyclerListView) Geocoder(android.location.Geocoder) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell)

Example 7 with TextSettingsCell

use of org.telegram.ui.Cells.TextSettingsCell in project Telegram-FOSS by Telegram-FOSS-Team.

the class ThemeActivity method createView.

@Override
public View createView(Context context) {
    lastIsDarkTheme = !Theme.isCurrentThemeDay();
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(false);
    if (AndroidUtilities.isTablet()) {
        actionBar.setOccupyStatusBar(false);
    }
    if (currentType == THEME_TYPE_THEMES_BROWSER) {
        actionBar.setTitle(LocaleController.getString("BrowseThemes", R.string.BrowseThemes));
        ActionBarMenu menu = actionBar.createMenu();
        sunDrawable = new RLottieDrawable(R.raw.sun, "" + R.raw.sun, AndroidUtilities.dp(28), AndroidUtilities.dp(28), true, null);
        if (lastIsDarkTheme) {
            sunDrawable.setCurrentFrame(sunDrawable.getFramesCount() - 1);
        } else {
            sunDrawable.setCurrentFrame(0);
        }
        sunDrawable.setPlayInDirectionOfCustomEndFrame(true);
        menuItem = menu.addItem(day_night_switch, sunDrawable);
    } else if (currentType == THEME_TYPE_BASIC) {
        actionBar.setTitle(LocaleController.getString("ChatSettings", R.string.ChatSettings));
        ActionBarMenu menu = actionBar.createMenu();
        menuItem = menu.addItem(0, R.drawable.ic_ab_other);
        menuItem.setContentDescription(LocaleController.getString("AccDescrMoreOptions", R.string.AccDescrMoreOptions));
        menuItem.addSubItem(share_theme, R.drawable.msg_share, LocaleController.getString("ShareTheme", R.string.ShareTheme));
        menuItem.addSubItem(edit_theme, R.drawable.msg_edit, LocaleController.getString("EditThemeColors", R.string.EditThemeColors));
        menuItem.addSubItem(create_theme, R.drawable.menu_palette, LocaleController.getString("CreateNewThemeMenu", R.string.CreateNewThemeMenu));
        menuItem.addSubItem(reset_settings, R.drawable.msg_reset, LocaleController.getString("ThemeResetToDefaults", R.string.ThemeResetToDefaults));
    } 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) {
                createNewTheme();
            } else if (id == share_theme) {
                Theme.ThemeInfo currentTheme = Theme.getCurrentTheme();
                Theme.ThemeAccent accent = currentTheme.getAccent(false);
                if (accent.info == null) {
                    getMessagesController().saveThemeToServer(accent.parentTheme, accent);
                    NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needShareTheme, accent.parentTheme, accent);
                } else {
                    String link = "https://" + getMessagesController().linkPrefix + "/addtheme/" + accent.info.slug;
                    showDialog(new ShareAlert(getParentActivity(), null, link, false, link, false));
                }
            } else if (id == edit_theme) {
                editTheme();
            } else if (id == reset_settings) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder1 = new AlertDialog.Builder(getParentActivity());
                builder1.setTitle(LocaleController.getString("ThemeResetToDefaultsTitle", R.string.ThemeResetToDefaultsTitle));
                builder1.setMessage(LocaleController.getString("ThemeResetToDefaultsText", R.string.ThemeResetToDefaultsText));
                builder1.setPositiveButton(LocaleController.getString("Reset", R.string.Reset), (dialogInterface, i) -> {
                    boolean changed = false;
                    if (setFontSize(AndroidUtilities.isTablet() ? 18 : 16)) {
                        changed = true;
                    }
                    if (setBubbleRadius(10, true)) {
                        changed = true;
                    }
                    if (changed) {
                        listAdapter.notifyItemChanged(textSizeRow, new Object());
                        listAdapter.notifyItemChanged(bubbleRadiusRow, new Object());
                    }
                    if (themesHorizontalListCell != null) {
                        Theme.ThemeInfo themeInfo = Theme.getTheme("Blue");
                        Theme.ThemeInfo currentTheme = Theme.getCurrentTheme();
                        Theme.ThemeAccent accent = themeInfo.themeAccentsMap.get(Theme.DEFALT_THEME_ACCENT_ID);
                        if (accent != null) {
                            Theme.OverrideWallpaperInfo info = new Theme.OverrideWallpaperInfo();
                            info.slug = Theme.DEFAULT_BACKGROUND_SLUG;
                            info.fileName = "Blue_99_wp.jpg";
                            info.originalFileName = "Blue_99_wp.jpg";
                            accent.overrideWallpaper = info;
                            themeInfo.setOverrideWallpaper(info);
                        }
                        if (themeInfo != currentTheme) {
                            themeInfo.setCurrentAccentId(Theme.DEFALT_THEME_ACCENT_ID);
                            Theme.saveThemeAccents(themeInfo, true, false, true, false);
                            themesHorizontalListCell.selectTheme(themeInfo);
                            themesHorizontalListCell.smoothScrollToPosition(0);
                        } else if (themeInfo.currentAccentId != Theme.DEFALT_THEME_ACCENT_ID) {
                            NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, currentTheme, currentType == THEME_TYPE_NIGHT, null, Theme.DEFALT_THEME_ACCENT_ID);
                            listAdapter.notifyItemChanged(themeAccentListRow);
                        } else {
                            Theme.reloadWallpaper();
                        }
                    }
                });
                builder1.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                AlertDialog alertDialog = builder1.create();
                showDialog(alertDialog);
                TextView button = (TextView) alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                if (button != null) {
                    button.setTextColor(Theme.getColor(Theme.key_dialogTextRed2));
                }
            } else if (id == day_night_switch) {
                SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("themeconfig", Activity.MODE_PRIVATE);
                String dayThemeName = preferences.getString("lastDayTheme", "Blue");
                if (Theme.getTheme(dayThemeName) == null || Theme.getTheme(dayThemeName).isDark()) {
                    dayThemeName = "Blue";
                }
                String nightThemeName = preferences.getString("lastDarkTheme", "Dark Blue");
                if (Theme.getTheme(nightThemeName) == null || !Theme.getTheme(nightThemeName).isDark()) {
                    nightThemeName = "Dark Blue";
                }
                Theme.ThemeInfo themeInfo = Theme.getActiveTheme();
                if (dayThemeName.equals(nightThemeName)) {
                    if (themeInfo.isDark() || dayThemeName.equals("Dark Blue") || dayThemeName.equals("Night")) {
                        dayThemeName = "Blue";
                    } else {
                        nightThemeName = "Dark Blue";
                    }
                }
                boolean toDark;
                if (toDark = dayThemeName.equals(themeInfo.getKey())) {
                    themeInfo = Theme.getTheme(nightThemeName);
                } else {
                    themeInfo = Theme.getTheme(dayThemeName);
                }
                int[] pos = new int[2];
                menuItem.getIconView().getLocationInWindow(pos);
                pos[0] += menuItem.getIconView().getMeasuredWidth() / 2;
                pos[1] += menuItem.getIconView().getMeasuredHeight() / 2;
                NotificationCenter.getGlobalInstance().postNotificationName(NotificationCenter.needSetDayNightTheme, themeInfo, false, pos, -1, toDark, menuItem.getIconView());
                updateRows(true);
            // AndroidUtilities.updateVisibleRows(listView);
            }
        }
    });
    listAdapter = new ListAdapter(context);
    FrameLayout frameLayout = new FrameLayout(context);
    frameLayout.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    fragmentView = frameLayout;
    listView = new RecyclerListView(context);
    listView.setLayoutManager(layoutManager = 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, x, y) -> {
        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 == distanceRow) {
            if (getParentActivity() == null) {
                return;
            }
            AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
            builder.setTitle(LocaleController.getString("DistanceUnitsTitle", R.string.DistanceUnitsTitle));
            builder.setItems(new CharSequence[] { LocaleController.getString("DistanceUnitsAutomatic", R.string.DistanceUnitsAutomatic), LocaleController.getString("DistanceUnitsKilometers", R.string.DistanceUnitsKilometers), LocaleController.getString("DistanceUnitsMiles", R.string.DistanceUnitsMiles) }, (dialog, which) -> {
                SharedConfig.setDistanceSystemType(which);
                RecyclerView.ViewHolder holder = listView.findViewHolderForAdapterPosition(distanceRow);
                if (holder != null) {
                    listAdapter.onBindViewHolder(holder, distanceRow);
                }
            });
            builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
            showDialog(builder.create());
        } 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(MediaDataController.TYPE_IMAGE));
        } else if (position == reactionsDoubleTapRow) {
            presentFragment(new ReactionsDoubleTapManageActivity());
        } else if (position == emojiRow) {
            SharedConfig.toggleBigEmoji();
            if (view instanceof TextCheckCell) {
                ((TextCheckCell) view).setChecked(SharedConfig.allowBigEmoji);
            }
        } else if (position == chatBlurRow) {
            SharedConfig.toggleChatBlur();
            if (view instanceof TextCheckCell) {
                ((TextCheckCell) view).setChecked(SharedConfig.chatBlurEnabled());
            }
        } else if (position == nightThemeRow) {
            if (LocaleController.isRTL && x <= AndroidUtilities.dp(76) || !LocaleController.isRTL && x >= view.getMeasuredWidth() - AndroidUtilities.dp(76)) {
                NotificationsCheckCell checkCell = (NotificationsCheckCell) view;
                if (Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_NONE) {
                    Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_AUTOMATIC;
                    checkCell.setChecked(true);
                } else {
                    Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_NONE;
                    checkCell.setChecked(false);
                }
                Theme.saveAutoNightThemeConfig();
                Theme.checkAutoNightThemeConditions(true);
                boolean enabled = Theme.selectedAutoNightType != Theme.AUTO_NIGHT_TYPE_NONE;
                String value = enabled ? Theme.getCurrentNightThemeName() : LocaleController.getString("AutoNightThemeOff", R.string.AutoNightThemeOff);
                if (enabled) {
                    String type;
                    if (Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SCHEDULED) {
                        type = LocaleController.getString("AutoNightScheduled", R.string.AutoNightScheduled);
                    } else if (Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SYSTEM) {
                        type = LocaleController.getString("AutoNightSystemDefault", R.string.AutoNightSystemDefault);
                    } else {
                        type = LocaleController.getString("AutoNightAdaptive", R.string.AutoNightAdaptive);
                    }
                    value = type + " " + value;
                }
                checkCell.setTextAndValueAndCheck(LocaleController.getString("AutoNightTheme", R.string.AutoNightTheme), value, enabled, true);
            } else {
                presentFragment(new ThemeActivity(THEME_TYPE_NIGHT));
            }
        } else if (position == nightDisabledRow) {
            if (Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_NONE) {
                return;
            }
            Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_NONE;
            updateRows(true);
            Theme.checkAutoNightThemeConditions();
        } else if (position == nightScheduledRow) {
            if (Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SCHEDULED) {
                return;
            }
            Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_SCHEDULED;
            if (Theme.autoNightScheduleByLocation) {
                updateSunTime(null, true);
            }
            updateRows(true);
            Theme.checkAutoNightThemeConditions();
        } else if (position == nightAutomaticRow) {
            if (Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_AUTOMATIC) {
                return;
            }
            Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_AUTOMATIC;
            updateRows(true);
            Theme.checkAutoNightThemeConditions();
        } else if (position == nightSystemDefaultRow) {
            if (Theme.selectedAutoNightType == Theme.AUTO_NIGHT_TYPE_SYSTEM) {
                return;
            }
            Theme.selectedAutoNightType = Theme.AUTO_NIGHT_TYPE_SYSTEM;
            updateRows(true);
            Theme.checkAutoNightThemeConditions();
        } else if (position == scheduleLocationRow) {
            Theme.autoNightScheduleByLocation = !Theme.autoNightScheduleByLocation;
            TextCheckCell checkCell = (TextCheckCell) view;
            checkCell.setChecked(Theme.autoNightScheduleByLocation);
            updateRows(true);
            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);
        } else if (position == createNewThemeRow) {
            createNewTheme();
        } else if (position == editThemeRow) {
            editTheme();
        }
    });
    return fragmentView;
}
Also used : AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Address(android.location.Address) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) Bundle(android.os.Bundle) SvgHelper(org.telegram.messenger.SvgHelper) PackageManager(android.content.pm.PackageManager) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) AndroidUtilities(org.telegram.messenger.AndroidUtilities) BrightnessControlCell(org.telegram.ui.Cells.BrightnessControlCell) LocationListener(android.location.LocationListener) Drawable(android.graphics.drawable.Drawable) Manifest(android.Manifest) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) Keep(androidx.annotation.Keep) ApplicationLoader(org.telegram.messenger.ApplicationLoader) TextCell(org.telegram.ui.Cells.TextCell) Locale(java.util.Locale) NotificationsCheckCell(org.telegram.ui.Cells.NotificationsCheckCell) ThemeEditorView(org.telegram.ui.Components.ThemeEditorView) View(android.view.View) Button(android.widget.Button) Canvas(android.graphics.Canvas) ChatMessageCell(org.telegram.ui.Cells.ChatMessageCell) RecyclerView(androidx.recyclerview.widget.RecyclerView) SunDate(org.telegram.messenger.time.SunDate) DocumentObject(org.telegram.messenger.DocumentObject) Utilities(org.telegram.messenger.Utilities) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) Geocoder(android.location.Geocoder) ViewGroup(android.view.ViewGroup) ShareAlert(org.telegram.ui.Components.ShareAlert) NotificationCenter(org.telegram.messenger.NotificationCenter) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) ThemeTypeCell(org.telegram.ui.Cells.ThemeTypeCell) List(java.util.List) TextView(android.widget.TextView) EmojiThemes(org.telegram.ui.ActionBar.EmojiThemes) TextPaint(android.text.TextPaint) FileProvider(androidx.core.content.FileProvider) Paint(android.graphics.Paint) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Location(android.location.Location) LocationManager(android.location.LocationManager) FileLoader(org.telegram.messenger.FileLoader) Context(android.content.Context) AccessibilityNodeInfo(android.view.accessibility.AccessibilityNodeInfo) TimePickerDialog(android.app.TimePickerDialog) Theme(org.telegram.ui.ActionBar.Theme) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) SwipeGestureSettingsView(org.telegram.ui.Components.SwipeGestureSettingsView) AlertsCreator(org.telegram.ui.Components.AlertsCreator) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) ArrayList(java.util.ArrayList) Calendar(java.util.Calendar) MotionEvent(android.view.MotionEvent) TLRPC(org.telegram.tgnet.TLRPC) ActionBar(org.telegram.ui.ActionBar.ActionBar) BuildConfig(org.telegram.messenger.BuildConfig) SharedConfig(org.telegram.messenger.SharedConfig) MediaDataController(org.telegram.messenger.MediaDataController) ChatListCell(org.telegram.ui.Cells.ChatListCell) Build(android.os.Build) SeekBarView(org.telegram.ui.Components.SeekBarView) DialogInterface(android.content.DialogInterface) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) ThemesHorizontalListCell(org.telegram.ui.Cells.ThemesHorizontalListCell) FileOutputStream(java.io.FileOutputStream) TextUtils(android.text.TextUtils) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) File(java.io.File) MessagesController(org.telegram.messenger.MessagesController) ThemePreviewMessagesCell(org.telegram.ui.Cells.ThemePreviewMessagesCell) Gravity(android.view.Gravity) SharedPreferences(android.content.SharedPreferences) TextCheckCell(org.telegram.ui.Cells.TextCheckCell) Activity(android.app.Activity) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Collections(java.util.Collections) RecyclerListView(org.telegram.ui.Components.RecyclerListView) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) TextCheckCell(org.telegram.ui.Cells.TextCheckCell) ShareAlert(org.telegram.ui.Components.ShareAlert) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) RecyclerListView(org.telegram.ui.Components.RecyclerListView) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) DefaultItemAnimator(androidx.recyclerview.widget.DefaultItemAnimator) TextView(android.widget.TextView) ActionBar(org.telegram.ui.ActionBar.ActionBar) SharedPreferences(android.content.SharedPreferences) TimePickerDialog(android.app.TimePickerDialog) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) NotificationsCheckCell(org.telegram.ui.Cells.NotificationsCheckCell) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) FrameLayout(android.widget.FrameLayout) Theme(org.telegram.ui.ActionBar.Theme) DocumentObject(org.telegram.messenger.DocumentObject)

Example 8 with TextSettingsCell

use of org.telegram.ui.Cells.TextSettingsCell in project Telegram-FOSS by Telegram-FOSS-Team.

the class PassportActivity method createIdentityInterface.

private void createIdentityInterface(final Context context) {
    languageMap = new HashMap<>();
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(context.getResources().getAssets().open("countries.txt")));
        String line;
        while ((line = reader.readLine()) != null) {
            String[] args = line.split(";");
            languageMap.put(args[1], args[2]);
        }
        reader.close();
    } catch (Exception e) {
        FileLog.e(e);
    }
    topErrorCell = new TextInfoPrivacyCell(context);
    topErrorCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_top, Theme.key_windowBackgroundGrayShadow));
    topErrorCell.setPadding(0, AndroidUtilities.dp(7), 0, 0);
    linearLayout2.addView(topErrorCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    checkTopErrorCell(true);
    if (currentDocumentsType != null) {
        headerCell = new HeaderCell(context);
        if (documentOnly) {
            headerCell.setText(LocaleController.getString("PassportDocuments", R.string.PassportDocuments));
        } else {
            headerCell.setText(LocaleController.getString("PassportRequiredDocuments", R.string.PassportRequiredDocuments));
        }
        headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
        linearLayout2.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        frontLayout = new LinearLayout(context);
        frontLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout2.addView(frontLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        uploadFrontCell = new TextDetailSettingsCell(context);
        uploadFrontCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        linearLayout2.addView(uploadFrontCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        uploadFrontCell.setOnClickListener(v -> {
            uploadingFileType = UPLOADING_TYPE_FRONT;
            openAttachMenu();
        });
        reverseLayout = new LinearLayout(context);
        reverseLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout2.addView(reverseLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        boolean divider = currentDocumentsType.selfie_required;
        uploadReverseCell = new TextDetailSettingsCell(context);
        uploadReverseCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        uploadReverseCell.setTextAndValue(LocaleController.getString("PassportReverseSide", R.string.PassportReverseSide), LocaleController.getString("PassportReverseSideInfo", R.string.PassportReverseSideInfo), divider);
        linearLayout2.addView(uploadReverseCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        uploadReverseCell.setOnClickListener(v -> {
            uploadingFileType = UPLOADING_TYPE_REVERSE;
            openAttachMenu();
        });
        if (currentDocumentsType.selfie_required) {
            selfieLayout = new LinearLayout(context);
            selfieLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout2.addView(selfieLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            uploadSelfieCell = new TextDetailSettingsCell(context);
            uploadSelfieCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
            uploadSelfieCell.setTextAndValue(LocaleController.getString("PassportSelfie", R.string.PassportSelfie), LocaleController.getString("PassportSelfieInfo", R.string.PassportSelfieInfo), currentType.translation_required);
            linearLayout2.addView(uploadSelfieCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            uploadSelfieCell.setOnClickListener(v -> {
                uploadingFileType = UPLOADING_TYPE_SELFIE;
                openAttachMenu();
            });
        }
        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
        bottomCell.setText(LocaleController.getString("PassportPersonalUploadInfo", R.string.PassportPersonalUploadInfo));
        linearLayout2.addView(bottomCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        if (currentDocumentsType.translation_required) {
            headerCell = new HeaderCell(context);
            headerCell.setText(LocaleController.getString("PassportTranslation", R.string.PassportTranslation));
            headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
            linearLayout2.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            translationLayout = new LinearLayout(context);
            translationLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout2.addView(translationLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            uploadTranslationCell = new TextSettingsCell(context);
            uploadTranslationCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
            linearLayout2.addView(uploadTranslationCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            uploadTranslationCell.setOnClickListener(v -> {
                uploadingFileType = UPLOADING_TYPE_TRANSLATION;
                openAttachMenu();
            });
            bottomCellTranslation = new TextInfoPrivacyCell(context);
            bottomCellTranslation.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
            if (currentBotId != 0) {
                noAllTranslationErrorText = LocaleController.getString("PassportAddTranslationUploadInfo", R.string.PassportAddTranslationUploadInfo);
            } else {
                if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypePassport) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddPassportInfo", R.string.PassportAddPassportInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeInternalPassport) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddInternalPassportInfo", R.string.PassportAddInternalPassportInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeIdentityCard) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddIdentityCardInfo", R.string.PassportAddIdentityCardInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeDriverLicense) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddDriverLicenceInfo", R.string.PassportAddDriverLicenceInfo);
                } else {
                    noAllTranslationErrorText = "";
                }
            }
            CharSequence text = noAllTranslationErrorText;
            if (documentsErrors != null) {
                String errorText;
                if ((errorText = documentsErrors.get("translation_all")) != null) {
                    SpannableStringBuilder stringBuilder = new SpannableStringBuilder(errorText);
                    stringBuilder.append("\n\n");
                    stringBuilder.append(noAllTranslationErrorText);
                    text = stringBuilder;
                    stringBuilder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteRedText3)), 0, errorText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    errorsValues.put("translation_all", "");
                }
            }
            bottomCellTranslation.setText(text);
            linearLayout2.addView(bottomCellTranslation, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        }
    } else if (Build.VERSION.SDK_INT >= 18) {
        scanDocumentCell = new TextSettingsCell(context);
        scanDocumentCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        scanDocumentCell.setText(LocaleController.getString("PassportScanPassport", R.string.PassportScanPassport), false);
        linearLayout2.addView(scanDocumentCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        scanDocumentCell.setOnClickListener(v -> {
            if (Build.VERSION.SDK_INT >= 23 && getParentActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                getParentActivity().requestPermissions(new String[] { Manifest.permission.CAMERA }, 22);
                return;
            }
            CameraScanActivity fragment = new CameraScanActivity(org.telegram.ui.CameraScanActivity.TYPE_MRZ);
            fragment.setDelegate(new CameraScanActivity.CameraScanActivityDelegate() {

                @Override
                public void didFindMrzInfo(MrzRecognizer.Result result) {
                    if (!TextUtils.isEmpty(result.firstName)) {
                        inputFields[FIELD_NAME].setText(result.firstName);
                    }
                    if (!TextUtils.isEmpty(result.middleName)) {
                        inputFields[FIELD_MIDNAME].setText(result.middleName);
                    }
                    if (!TextUtils.isEmpty(result.lastName)) {
                        inputFields[FIELD_SURNAME].setText(result.lastName);
                    }
                    if (result.gender != MrzRecognizer.Result.GENDER_UNKNOWN) {
                        switch(result.gender) {
                            case MrzRecognizer.Result.GENDER_MALE:
                                currentGender = "male";
                                inputFields[FIELD_GENDER].setText(LocaleController.getString("PassportMale", R.string.PassportMale));
                                break;
                            case MrzRecognizer.Result.GENDER_FEMALE:
                                currentGender = "female";
                                inputFields[FIELD_GENDER].setText(LocaleController.getString("PassportFemale", R.string.PassportFemale));
                                break;
                        }
                    }
                    if (!TextUtils.isEmpty(result.nationality)) {
                        currentCitizeship = result.nationality;
                        String country = languageMap.get(currentCitizeship);
                        if (country != null) {
                            inputFields[FIELD_CITIZENSHIP].setText(country);
                        }
                    }
                    if (!TextUtils.isEmpty(result.issuingCountry)) {
                        currentResidence = result.issuingCountry;
                        String country = languageMap.get(currentResidence);
                        if (country != null) {
                            inputFields[FIELD_RESIDENCE].setText(country);
                        }
                    }
                    if (result.birthDay > 0 && result.birthMonth > 0 && result.birthYear > 0) {
                        inputFields[FIELD_BIRTHDAY].setText(String.format(Locale.US, "%02d.%02d.%d", result.birthDay, result.birthMonth, result.birthYear));
                    }
                }
            });
            presentFragment(fragment);
        });
        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
        bottomCell.setText(LocaleController.getString("PassportScanPassportInfo", R.string.PassportScanPassportInfo));
        linearLayout2.addView(bottomCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    headerCell = new HeaderCell(context);
    if (documentOnly) {
        headerCell.setText(LocaleController.getString("PassportDocument", R.string.PassportDocument));
    } else {
        headerCell.setText(LocaleController.getString("PassportPersonal", R.string.PassportPersonal));
    }
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    int count = currentDocumentsType != null ? FIELD_IDENTITY_COUNT : FIELD_IDENTITY_NODOC_COUNT;
    inputFields = new EditTextBoldCursor[count];
    for (int a = 0; a < count; a++) {
        final EditTextBoldCursor field = new EditTextBoldCursor(context);
        inputFields[a] = field;
        ViewGroup container = new FrameLayout(context) {

            private StaticLayout errorLayout;

            private float offsetX;

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                int width = MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(34);
                errorLayout = field.getErrorLayout(width);
                if (errorLayout != null) {
                    int lineCount = errorLayout.getLineCount();
                    if (lineCount > 1) {
                        int height = AndroidUtilities.dp(64) + (errorLayout.getLineBottom(lineCount - 1) - errorLayout.getLineBottom(0));
                        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
                    }
                    if (LocaleController.isRTL) {
                        float maxW = 0;
                        for (int a = 0; a < lineCount; a++) {
                            float l = errorLayout.getLineLeft(a);
                            if (l != 0) {
                                offsetX = 0;
                                break;
                            }
                            maxW = Math.max(maxW, errorLayout.getLineWidth(a));
                            if (a == lineCount - 1) {
                                offsetX = width - maxW;
                            }
                        }
                    }
                }
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                if (errorLayout != null) {
                    canvas.save();
                    canvas.translate(AndroidUtilities.dp(21) + offsetX, field.getLineY() + AndroidUtilities.dp(3));
                    errorLayout.draw(canvas);
                    canvas.restore();
                }
            }
        };
        container.setWillNotDraw(false);
        linearLayout2.addView(container, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 64));
        container.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
        if (a == count - 1) {
            extraBackgroundView = new View(context);
            extraBackgroundView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
            linearLayout2.addView(extraBackgroundView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 6));
        }
        if (documentOnly && currentDocumentsType != null && a < FIELD_CARDNUMBER) {
            container.setVisibility(View.GONE);
            if (extraBackgroundView != null) {
                extraBackgroundView.setVisibility(View.GONE);
            }
        }
        inputFields[a].setTag(a);
        inputFields[a].setSupportRtlHint(true);
        inputFields[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        inputFields[a].setHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
        inputFields[a].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputFields[a].setHeaderHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader));
        inputFields[a].setTransformHintToHeader(true);
        inputFields[a].setBackgroundDrawable(null);
        inputFields[a].setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputFields[a].setCursorSize(AndroidUtilities.dp(20));
        inputFields[a].setCursorWidth(1.5f);
        inputFields[a].setLineColors(Theme.getColor(Theme.key_windowBackgroundWhiteInputField), Theme.getColor(Theme.key_windowBackgroundWhiteInputFieldActivated), Theme.getColor(Theme.key_windowBackgroundWhiteRedText3));
        if (a == FIELD_CITIZENSHIP || a == FIELD_RESIDENCE) {
            inputFields[a].setOnTouchListener((v, event) -> {
                if (getParentActivity() == null) {
                    return false;
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    CountrySelectActivity fragment = new CountrySelectActivity(false);
                    fragment.setCountrySelectActivityDelegate((country) -> {
                        int field12 = (Integer) v.getTag();
                        final EditTextBoldCursor editText = inputFields[field12];
                        if (field12 == FIELD_CITIZENSHIP) {
                            currentCitizeship = country.shortname;
                        } else {
                            currentResidence = country.shortname;
                        }
                        editText.setText(country.name);
                    });
                    presentFragment(fragment);
                }
                return true;
            });
            inputFields[a].setInputType(0);
        } else if (a == FIELD_BIRTHDAY || a == FIELD_EXPIRE) {
            inputFields[a].setOnTouchListener((v, event) -> {
                if (getParentActivity() == null) {
                    return false;
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Calendar calendar = Calendar.getInstance();
                    int year = calendar.get(Calendar.YEAR);
                    int monthOfYear = calendar.get(Calendar.MONTH);
                    int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
                    try {
                        final EditTextBoldCursor field1 = (EditTextBoldCursor) v;
                        int num = (Integer) field1.getTag();
                        int minYear;
                        int maxYear;
                        int currentYearDiff;
                        String title;
                        if (num == FIELD_EXPIRE) {
                            title = LocaleController.getString("PassportSelectExpiredDate", R.string.PassportSelectExpiredDate);
                            minYear = 0;
                            maxYear = 20;
                            currentYearDiff = 0;
                        } else {
                            title = LocaleController.getString("PassportSelectBithdayDate", R.string.PassportSelectBithdayDate);
                            minYear = -120;
                            maxYear = 0;
                            currentYearDiff = -18;
                        }
                        int selectedDay = -1;
                        int selectedMonth = -1;
                        int selectedYear = -1;
                        String[] args = field1.getText().toString().split("\\.");
                        if (args.length == 3) {
                            selectedDay = Utilities.parseInt(args[0]);
                            selectedMonth = Utilities.parseInt(args[1]);
                            selectedYear = Utilities.parseInt(args[2]);
                        }
                        AlertDialog.Builder builder = AlertsCreator.createDatePickerDialog(context, minYear, maxYear, currentYearDiff, selectedDay, selectedMonth, selectedYear, title, num == FIELD_EXPIRE, (year1, month, dayOfMonth1) -> {
                            if (num == FIELD_EXPIRE) {
                                currentExpireDate[0] = year1;
                                currentExpireDate[1] = month + 1;
                                currentExpireDate[2] = dayOfMonth1;
                            }
                            field1.setText(String.format(Locale.US, "%02d.%02d.%d", dayOfMonth1, month + 1, year1));
                        });
                        if (num == FIELD_EXPIRE) {
                            builder.setNegativeButton(LocaleController.getString("PassportSelectNotExpire", R.string.PassportSelectNotExpire), (dialog, which) -> {
                                currentExpireDate[0] = currentExpireDate[1] = currentExpireDate[2] = 0;
                                field1.setText(LocaleController.getString("PassportNoExpireDate", R.string.PassportNoExpireDate));
                            });
                        }
                        showDialog(builder.create());
                    } catch (Exception e) {
                        FileLog.e(e);
                    }
                }
                return true;
            });
            inputFields[a].setInputType(0);
            inputFields[a].setFocusable(false);
        } else if (a == FIELD_GENDER) {
            inputFields[a].setOnTouchListener((v, event) -> {
                if (getParentActivity() == null) {
                    return false;
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                    builder.setTitle(LocaleController.getString("PassportSelectGender", R.string.PassportSelectGender));
                    builder.setItems(new CharSequence[] { LocaleController.getString("PassportMale", R.string.PassportMale), LocaleController.getString("PassportFemale", R.string.PassportFemale) }, (dialogInterface, i) -> {
                        if (i == 0) {
                            currentGender = "male";
                            inputFields[FIELD_GENDER].setText(LocaleController.getString("PassportMale", R.string.PassportMale));
                        } else if (i == 1) {
                            currentGender = "female";
                            inputFields[FIELD_GENDER].setText(LocaleController.getString("PassportFemale", R.string.PassportFemale));
                        }
                    });
                    builder.setPositiveButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                    showDialog(builder.create());
                }
                return true;
            });
            inputFields[a].setInputType(0);
            inputFields[a].setFocusable(false);
        } else {
            inputFields[a].setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
            inputFields[a].setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        }
        String value;
        final String key;
        HashMap<String, String> values;
        switch(a) {
            case FIELD_NAME:
                if (currentType.native_names) {
                    inputFields[a].setHintText(LocaleController.getString("PassportNameLatin", R.string.PassportNameLatin));
                } else {
                    inputFields[a].setHintText(LocaleController.getString("PassportName", R.string.PassportName));
                }
                key = "first_name";
                values = currentValues;
                break;
            case FIELD_MIDNAME:
                if (currentType.native_names) {
                    inputFields[a].setHintText(LocaleController.getString("PassportMidnameLatin", R.string.PassportMidnameLatin));
                } else {
                    inputFields[a].setHintText(LocaleController.getString("PassportMidname", R.string.PassportMidname));
                }
                key = "middle_name";
                values = currentValues;
                break;
            case FIELD_SURNAME:
                if (currentType.native_names) {
                    inputFields[a].setHintText(LocaleController.getString("PassportSurnameLatin", R.string.PassportSurnameLatin));
                } else {
                    inputFields[a].setHintText(LocaleController.getString("PassportSurname", R.string.PassportSurname));
                }
                key = "last_name";
                values = currentValues;
                break;
            case FIELD_BIRTHDAY:
                inputFields[a].setHintText(LocaleController.getString("PassportBirthdate", R.string.PassportBirthdate));
                key = "birth_date";
                values = currentValues;
                break;
            case FIELD_GENDER:
                inputFields[a].setHintText(LocaleController.getString("PassportGender", R.string.PassportGender));
                key = "gender";
                values = currentValues;
                break;
            case FIELD_CITIZENSHIP:
                inputFields[a].setHintText(LocaleController.getString("PassportCitizenship", R.string.PassportCitizenship));
                key = "country_code";
                values = currentValues;
                break;
            case FIELD_RESIDENCE:
                inputFields[a].setHintText(LocaleController.getString("PassportResidence", R.string.PassportResidence));
                key = "residence_country_code";
                values = currentValues;
                break;
            case FIELD_CARDNUMBER:
                inputFields[a].setHintText(LocaleController.getString("PassportDocumentNumber", R.string.PassportDocumentNumber));
                key = "document_no";
                values = currentDocumentValues;
                break;
            case FIELD_EXPIRE:
                inputFields[a].setHintText(LocaleController.getString("PassportExpired", R.string.PassportExpired));
                key = "expiry_date";
                values = currentDocumentValues;
                break;
            default:
                continue;
        }
        setFieldValues(values, inputFields[a], key);
        inputFields[a].setSelection(inputFields[a].length());
        if (a == FIELD_NAME || a == FIELD_SURNAME || a == FIELD_MIDNAME) {
            inputFields[a].addTextChangedListener(new TextWatcher() {

                private boolean ignore;

                @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) {
                    if (ignore) {
                        return;
                    }
                    int num = (Integer) field.getTag();
                    boolean error = false;
                    for (int a = 0; a < s.length(); a++) {
                        char ch = s.charAt(a);
                        if (!(ch >= '0' && ch <= '9' || ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == ' ' || ch == '\'' || ch == ',' || ch == '.' || ch == '&' || ch == '-' || ch == '/')) {
                            error = true;
                            break;
                        }
                    }
                    if (error && !allowNonLatinName) {
                        field.setErrorText(LocaleController.getString("PassportUseLatinOnly", R.string.PassportUseLatinOnly));
                    } else {
                        nonLatinNames[num] = error;
                        checkFieldForError(field, key, s, false);
                    }
                }
            });
        } else {
            inputFields[a].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) {
                    checkFieldForError(field, key, s, values == currentDocumentValues);
                    int field12 = (Integer) field.getTag();
                    final EditTextBoldCursor editText = inputFields[field12];
                    if (field12 == FIELD_RESIDENCE) {
                        checkNativeFields(true);
                    }
                }
            });
        }
        inputFields[a].setPadding(0, 0, 0, 0);
        inputFields[a].setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
        container.addView(inputFields[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 21, 0, 21, 0));
        inputFields[a].setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_NEXT) {
                int num = (Integer) textView.getTag();
                num++;
                if (num < inputFields.length) {
                    if (inputFields[num].isFocusable()) {
                        inputFields[num].requestFocus();
                    } else {
                        inputFields[num].dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0, 0, 0));
                        textView.clearFocus();
                        AndroidUtilities.hideKeyboard(textView);
                    }
                }
                return true;
            }
            return false;
        });
    }
    sectionCell2 = new ShadowSectionCell(context);
    linearLayout2.addView(sectionCell2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    headerCell = new HeaderCell(context);
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    inputExtraFields = new EditTextBoldCursor[FIELD_NATIVE_COUNT];
    for (int a = 0; a < FIELD_NATIVE_COUNT; a++) {
        final EditTextBoldCursor field = new EditTextBoldCursor(context);
        inputExtraFields[a] = field;
        ViewGroup container = new FrameLayout(context) {

            private StaticLayout errorLayout;

            private float offsetX;

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                int width = MeasureSpec.getSize(widthMeasureSpec) - AndroidUtilities.dp(34);
                errorLayout = field.getErrorLayout(width);
                if (errorLayout != null) {
                    int lineCount = errorLayout.getLineCount();
                    if (lineCount > 1) {
                        int height = AndroidUtilities.dp(64) + (errorLayout.getLineBottom(lineCount - 1) - errorLayout.getLineBottom(0));
                        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
                    }
                    if (LocaleController.isRTL) {
                        float maxW = 0;
                        for (int a = 0; a < lineCount; a++) {
                            float l = errorLayout.getLineLeft(a);
                            if (l != 0) {
                                offsetX = 0;
                                break;
                            }
                            maxW = Math.max(maxW, errorLayout.getLineWidth(a));
                            if (a == lineCount - 1) {
                                offsetX = width - maxW;
                            }
                        }
                    }
                }
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }

            @Override
            protected void onDraw(Canvas canvas) {
                if (errorLayout != null) {
                    canvas.save();
                    canvas.translate(AndroidUtilities.dp(21) + offsetX, field.getLineY() + AndroidUtilities.dp(3));
                    errorLayout.draw(canvas);
                    canvas.restore();
                }
            }
        };
        container.setWillNotDraw(false);
        linearLayout2.addView(container, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 64));
        container.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
        if (a == FIELD_NATIVE_COUNT - 1) {
            extraBackgroundView2 = new View(context);
            extraBackgroundView2.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
            linearLayout2.addView(extraBackgroundView2, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 6));
        }
        inputExtraFields[a].setTag(a);
        inputExtraFields[a].setSupportRtlHint(true);
        inputExtraFields[a].setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
        inputExtraFields[a].setHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
        inputExtraFields[a].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputExtraFields[a].setHeaderHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader));
        inputExtraFields[a].setTransformHintToHeader(true);
        inputExtraFields[a].setBackgroundDrawable(null);
        inputExtraFields[a].setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        inputExtraFields[a].setCursorSize(AndroidUtilities.dp(20));
        inputExtraFields[a].setCursorWidth(1.5f);
        inputExtraFields[a].setLineColors(Theme.getColor(Theme.key_windowBackgroundWhiteInputField), Theme.getColor(Theme.key_windowBackgroundWhiteInputFieldActivated), Theme.getColor(Theme.key_windowBackgroundWhiteRedText3));
        inputExtraFields[a].setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
        inputExtraFields[a].setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_EXTRACT_UI);
        String value;
        final String key;
        HashMap<String, String> values;
        switch(a) {
            case FIELD_NATIVE_NAME:
                key = "first_name_native";
                values = currentValues;
                break;
            case FIELD_NATIVE_MIDNAME:
                key = "middle_name_native";
                values = currentValues;
                break;
            case FIELD_NATIVE_SURNAME:
                key = "last_name_native";
                values = currentValues;
                break;
            default:
                continue;
        }
        setFieldValues(values, inputExtraFields[a], key);
        inputExtraFields[a].setSelection(inputExtraFields[a].length());
        if (a == FIELD_NATIVE_NAME || a == FIELD_NATIVE_SURNAME || a == FIELD_NATIVE_MIDNAME) {
            inputExtraFields[a].addTextChangedListener(new TextWatcher() {

                private boolean ignore;

                @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) {
                    if (ignore) {
                        return;
                    }
                    checkFieldForError(field, key, s, false);
                }
            });
        }
        inputExtraFields[a].setPadding(0, 0, 0, 0);
        inputExtraFields[a].setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
        container.addView(inputExtraFields[a], LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 21, 0, 21, 0));
        inputExtraFields[a].setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_NEXT) {
                int num = (Integer) textView.getTag();
                num++;
                if (num < inputExtraFields.length) {
                    if (inputExtraFields[num].isFocusable()) {
                        inputExtraFields[num].requestFocus();
                    } else {
                        inputExtraFields[num].dispatchTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 0, 0, 0));
                        textView.clearFocus();
                        AndroidUtilities.hideKeyboard(textView);
                    }
                }
                return true;
            }
            return false;
        });
    }
    nativeInfoCell = new TextInfoPrivacyCell(context);
    linearLayout2.addView(nativeInfoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    if ((currentBotId != 0 || currentDocumentsType == null) && currentTypeValue != null && !documentOnly || currentDocumentsTypeValue != null) {
        if (currentDocumentsTypeValue != null) {
            addDocumentViews(currentDocumentsTypeValue.files);
            if (currentDocumentsTypeValue.front_side instanceof TLRPC.TL_secureFile) {
                addDocumentViewInternal((TLRPC.TL_secureFile) currentDocumentsTypeValue.front_side, UPLOADING_TYPE_FRONT);
            }
            if (currentDocumentsTypeValue.reverse_side instanceof TLRPC.TL_secureFile) {
                addDocumentViewInternal((TLRPC.TL_secureFile) currentDocumentsTypeValue.reverse_side, UPLOADING_TYPE_REVERSE);
            }
            if (currentDocumentsTypeValue.selfie instanceof TLRPC.TL_secureFile) {
                addDocumentViewInternal((TLRPC.TL_secureFile) currentDocumentsTypeValue.selfie, UPLOADING_TYPE_SELFIE);
            }
            addTranslationDocumentViews(currentDocumentsTypeValue.translation);
        }
        TextSettingsCell settingsCell1 = new TextSettingsCell(context);
        settingsCell1.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText3));
        settingsCell1.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        if (currentDocumentsType == null) {
            settingsCell1.setText(LocaleController.getString("PassportDeleteInfo", R.string.PassportDeleteInfo), false);
        } else {
            settingsCell1.setText(LocaleController.getString("PassportDeleteDocument", R.string.PassportDeleteDocument), false);
        }
        linearLayout2.addView(settingsCell1, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        settingsCell1.setOnClickListener(v -> createDocumentDeleteAlert());
        nativeInfoCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
        sectionCell = new ShadowSectionCell(context);
        sectionCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
        linearLayout2.addView(sectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    } else {
        nativeInfoCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
    }
    updateInterfaceStringsForDocumentType();
    checkNativeFields(false);
}
Also used : RandomAccessFile(java.io.RandomAccessFile) Arrays(java.util.Arrays) Bundle(android.os.Bundle) Uri(android.net.Uri) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) Manifest(android.Manifest) RSAPublicKey(java.security.interfaces.RSAPublicKey) MediaStore(android.provider.MediaStore) Canvas(android.graphics.Canvas) TimerTask(java.util.TimerTask) ForegroundColorSpan(android.text.style.ForegroundColorSpan) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) NotificationCenter(org.telegram.messenger.NotificationCenter) TextPaint(android.text.TextPaint) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) Paint(android.graphics.Paint) InputFilter(android.text.InputFilter) RadialProgress(org.telegram.ui.Components.RadialProgress) TextWatcher(android.text.TextWatcher) FileLoader(org.telegram.messenger.FileLoader) SlideView(org.telegram.ui.Components.SlideView) RequestDelegate(org.telegram.tgnet.RequestDelegate) Dialog(android.app.Dialog) URLSpanNoUnderline(org.telegram.ui.Components.URLSpanNoUnderline) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) Calendar(java.util.Calendar) TextDetailSettingsCell(org.telegram.ui.Cells.TextDetailSettingsCell) TLRPC(org.telegram.tgnet.TLRPC) Toast(android.widget.Toast) PhoneFormat(org.telegram.PhoneFormat.PhoneFormat) Menu(android.view.Menu) BuildConfig(org.telegram.messenger.BuildConfig) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) HintEditText(org.telegram.ui.Components.HintEditText) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) TextUtils(android.text.TextUtils) InputStreamReader(java.io.InputStreamReader) File(java.io.File) Gravity(android.view.Gravity) UserObject(org.telegram.messenger.UserObject) SharedPreferences(android.content.SharedPreferences) TypedValue(android.util.TypedValue) ScrollView(android.widget.ScrollView) BufferedReader(java.io.BufferedReader) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) Rect(android.graphics.Rect) ActionMode(android.view.ActionMode) LinearLayout(android.widget.LinearLayout) ActionBarMenuItem(org.telegram.ui.ActionBar.ActionBarMenuItem) PackageManager(android.content.pm.PackageManager) Spannable(android.text.Spannable) AndroidUtilities(org.telegram.messenger.AndroidUtilities) ClickableSpan(android.text.style.ClickableSpan) Timer(java.util.Timer) Animator(android.animation.Animator) AccelerateDecelerateInterpolator(android.view.animation.AccelerateDecelerateInterpolator) CheckBoxCell(org.telegram.ui.Cells.CheckBoxCell) MrzRecognizer(org.telegram.messenger.MrzRecognizer) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) JSONObject(org.json.JSONObject) ApplicationLoader(org.telegram.messenger.ApplicationLoader) Locale(java.util.Locale) MediaController(org.telegram.messenger.MediaController) View(android.view.View) ImageLoader(org.telegram.messenger.ImageLoader) ContextProgressView(org.telegram.ui.Components.ContextProgressView) Utilities(org.telegram.messenger.Utilities) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) ObjectAnimator(android.animation.ObjectAnimator) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) PorterDuff(android.graphics.PorterDuff) SendMessagesHelper(org.telegram.messenger.SendMessagesHelper) ConnectionsManager(org.telegram.tgnet.ConnectionsManager) ViewGroup(android.view.ViewGroup) KeyFactory(java.security.KeyFactory) UserConfig(org.telegram.messenger.UserConfig) TextView(android.widget.TextView) FileProvider(androidx.core.content.FileProvider) EditorInfo(android.view.inputmethod.EditorInfo) Typeface(android.graphics.Typeface) Context(android.content.Context) StaticLayout(android.text.StaticLayout) Spanned(android.text.Spanned) KeyEvent(android.view.KeyEvent) Theme(org.telegram.ui.ActionBar.Theme) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HashMap(java.util.HashMap) HeaderCell(org.telegram.ui.Cells.HeaderCell) PackageInfo(android.content.pm.PackageInfo) Cipher(javax.crypto.Cipher) MenuItem(android.view.MenuItem) SuppressLint(android.annotation.SuppressLint) PhoneNumberUtils(android.telephony.PhoneNumberUtils) MotionEvent(android.view.MotionEvent) SRPHelper(org.telegram.messenger.SRPHelper) SecureDocument(org.telegram.messenger.SecureDocument) TelephonyManager(android.telephony.TelephonyManager) ActionBar(org.telegram.ui.ActionBar.ActionBar) TLObject(org.telegram.tgnet.TLObject) AnimatorSet(android.animation.AnimatorSet) MessageObject(org.telegram.messenger.MessageObject) SharedConfig(org.telegram.messenger.SharedConfig) PasswordTransformationMethod(android.text.method.PasswordTransformationMethod) BuildVars(org.telegram.messenger.BuildVars) Build(android.os.Build) DownloadController(org.telegram.messenger.DownloadController) DialogInterface(android.content.DialogInterface) Browser(org.telegram.messenger.browser.Browser) Iterator(java.util.Iterator) BackupImageView(org.telegram.ui.Components.BackupImageView) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) SecureDocumentKey(org.telegram.messenger.SecureDocumentKey) ChatAttachAlert(org.telegram.ui.Components.ChatAttachAlert) Bitmap(android.graphics.Bitmap) Base64(android.util.Base64) Vibrator(android.os.Vibrator) Comparator(java.util.Comparator) Activity(android.app.Activity) Collections(java.util.Collections) JSONArray(org.json.JSONArray) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) HeaderCell(org.telegram.ui.Cells.HeaderCell) SpannableStringBuilder(android.text.SpannableStringBuilder) TLRPC(org.telegram.tgnet.TLRPC) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) InputStreamReader(java.io.InputStreamReader) TextDetailSettingsCell(org.telegram.ui.Cells.TextDetailSettingsCell) ForegroundColorSpan(android.text.style.ForegroundColorSpan) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) ViewGroup(android.view.ViewGroup) Canvas(android.graphics.Canvas) Calendar(java.util.Calendar) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) StaticLayout(android.text.StaticLayout) ImageView(android.widget.ImageView) SlideView(org.telegram.ui.Components.SlideView) ScrollView(android.widget.ScrollView) View(android.view.View) ContextProgressView(org.telegram.ui.Components.ContextProgressView) EmptyTextProgressView(org.telegram.ui.Components.EmptyTextProgressView) TextView(android.widget.TextView) BackupImageView(org.telegram.ui.Components.BackupImageView) TextPaint(android.text.TextPaint) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) FrameLayout(android.widget.FrameLayout) BufferedReader(java.io.BufferedReader) LinearLayout(android.widget.LinearLayout) SpannableStringBuilder(android.text.SpannableStringBuilder)

Example 9 with TextSettingsCell

use of org.telegram.ui.Cells.TextSettingsCell in project Telegram-FOSS by Telegram-FOSS-Team.

the class ChatEditActivity method createView.

@Override
public View createView(Context context) {
    if (nameTextView != null) {
        nameTextView.onDestroy();
    }
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (checkDiscard()) {
                    finishFragment();
                }
            } else if (id == done_button) {
                processDone();
            }
        }
    });
    SizeNotifierFrameLayout sizeNotifierFrameLayout = new SizeNotifierFrameLayout(context) {

        private boolean ignoreLayout;

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            setMeasuredDimension(widthSize, heightSize);
            heightSize -= getPaddingTop();
            measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int keyboardSize = measureKeyboardHeight();
            if (keyboardSize > AndroidUtilities.dp(20)) {
                ignoreLayout = true;
                nameTextView.hideEmojiView();
                ignoreLayout = false;
            }
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (child == null || child.getVisibility() == GONE || child == actionBar) {
                    continue;
                }
                if (nameTextView != null && nameTextView.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow || AndroidUtilities.isTablet()) {
                        if (AndroidUtilities.isTablet()) {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(AndroidUtilities.isTablet() ? 200 : 320), heightSize - AndroidUtilities.statusBarHeight + getPaddingTop()), MeasureSpec.EXACTLY));
                        } else {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - AndroidUtilities.statusBarHeight + getPaddingTop(), MeasureSpec.EXACTLY));
                        }
                    } else {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
                    }
                } else {
                    measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                }
            }
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            final int count = getChildCount();
            int keyboardSize = measureKeyboardHeight();
            int paddingBottom = keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet() ? nameTextView.getEmojiPadding() : 0;
            setBottomClip(paddingBottom);
            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child.getVisibility() == GONE) {
                    continue;
                }
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();
                int childLeft;
                int childTop;
                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = Gravity.TOP | Gravity.LEFT;
                }
                final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
                switch(absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
                        break;
                    case Gravity.RIGHT:
                        childLeft = r - width - lp.rightMargin;
                        break;
                    case Gravity.LEFT:
                    default:
                        childLeft = lp.leftMargin;
                }
                switch(verticalGravity) {
                    case Gravity.TOP:
                        childTop = lp.topMargin + getPaddingTop();
                        break;
                    case Gravity.CENTER_VERTICAL:
                        childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
                        break;
                    case Gravity.BOTTOM:
                        childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
                        break;
                    default:
                        childTop = lp.topMargin;
                }
                if (nameTextView != null && nameTextView.isPopupView(child)) {
                    if (AndroidUtilities.isTablet()) {
                        childTop = getMeasuredHeight() - child.getMeasuredHeight();
                    } else {
                        childTop = getMeasuredHeight() + keyboardSize - child.getMeasuredHeight();
                    }
                }
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
            notifyHeightChanged();
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    sizeNotifierFrameLayout.setOnTouchListener((v, event) -> true);
    fragmentView = sizeNotifierFrameLayout;
    fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));
    ScrollView scrollView = new ScrollView(context);
    scrollView.setFillViewport(true);
    sizeNotifierFrameLayout.addView(scrollView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    LinearLayout linearLayout1 = new LinearLayout(context);
    scrollView.addView(linearLayout1, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    linearLayout1.setOrientation(LinearLayout.VERTICAL);
    actionBar.setTitle(LocaleController.getString("ChannelEdit", R.string.ChannelEdit));
    avatarContainer = new LinearLayout(context);
    avatarContainer.setOrientation(LinearLayout.VERTICAL);
    avatarContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout1.addView(avatarContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    FrameLayout frameLayout = new FrameLayout(context);
    avatarContainer.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    avatarImage = new BackupImageView(context) {

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

        @Override
        public void invalidate(int l, int t, int r, int b) {
            if (avatarOverlay != null) {
                avatarOverlay.invalidate();
            }
            super.invalidate(l, t, r, b);
        }
    };
    avatarImage.setRoundRadius(AndroidUtilities.dp(32));
    if (ChatObject.canChangeChatInfo(currentChat)) {
        frameLayout.addView(avatarImage, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 12, LocaleController.isRTL ? 16 : 0, 8));
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(0x55000000);
        avatarOverlay = new View(context) {

            @Override
            protected void onDraw(Canvas canvas) {
                if (avatarImage != null && avatarImage.getImageReceiver().hasNotThumb()) {
                    paint.setAlpha((int) (0x55 * avatarImage.getImageReceiver().getCurrentAlpha()));
                    canvas.drawCircle(getMeasuredWidth() / 2.0f, getMeasuredHeight() / 2.0f, getMeasuredWidth() / 2.0f, paint);
                }
            }
        };
        frameLayout.addView(avatarOverlay, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 12, LocaleController.isRTL ? 16 : 0, 8));
        avatarProgressView = new RadialProgressView(context);
        avatarProgressView.setSize(AndroidUtilities.dp(30));
        avatarProgressView.setProgressColor(0xffffffff);
        avatarProgressView.setNoProgress(false);
        frameLayout.addView(avatarProgressView, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 12, LocaleController.isRTL ? 16 : 0, 8));
        showAvatarProgress(false, false);
        avatarContainer.setOnClickListener(v -> {
            if (imageUpdater.isUploadingImage()) {
                return;
            }
            TLRPC.Chat chat = getMessagesController().getChat(chatId);
            if (chat.photo != null && chat.photo.photo_big != null) {
                PhotoViewer.getInstance().setParentActivity(getParentActivity());
                if (chat.photo.dc_id != 0) {
                    chat.photo.photo_big.dc_id = chat.photo.dc_id;
                }
                ImageLocation videoLocation;
                if (info != null && (info.chat_photo instanceof TLRPC.TL_photo) && !info.chat_photo.video_sizes.isEmpty()) {
                    videoLocation = ImageLocation.getForPhoto(info.chat_photo.video_sizes.get(0), info.chat_photo);
                } else {
                    videoLocation = null;
                }
                PhotoViewer.getInstance().openPhotoWithVideo(chat.photo.photo_big, videoLocation, provider);
            }
        });
    } else {
        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));
    }
    nameTextView = new EditTextEmoji(context, sizeNotifierFrameLayout, this, EditTextEmoji.STYLE_FRAGMENT);
    if (isChannel) {
        nameTextView.setHint(LocaleController.getString("EnterChannelName", R.string.EnterChannelName));
    } else {
        nameTextView.setHint(LocaleController.getString("GroupName", R.string.GroupName));
    }
    nameTextView.setEnabled(ChatObject.canChangeChatInfo(currentChat));
    nameTextView.setFocusable(nameTextView.isEnabled());
    nameTextView.getEditText().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.getText().toString(), null);
            if (avatarImage != null) {
                avatarImage.invalidate();
            }
        }
    });
    InputFilter[] inputFilters = new InputFilter[1];
    inputFilters[0] = new InputFilter.LengthFilter(128);
    nameTextView.setFilters(inputFilters);
    frameLayout.addView(nameTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 5 : 96, 0, LocaleController.isRTL ? 96 : 5, 0));
    settingsContainer = new LinearLayout(context);
    settingsContainer.setOrientation(LinearLayout.VERTICAL);
    settingsContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout1.addView(settingsContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    if (ChatObject.canChangeChatInfo(currentChat)) {
        setAvatarCell = new TextCell(context) {

            @Override
            protected void onDraw(Canvas canvas) {
                canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(20), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(20) : 0), getMeasuredHeight() - 1, Theme.dividerPaint);
            }
        };
        setAvatarCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        setAvatarCell.setColors(Theme.key_windowBackgroundWhiteBlueIcon, Theme.key_windowBackgroundWhiteBlueButton);
        setAvatarCell.setOnClickListener(v -> {
            imageUpdater.openMenu(avatar != null, () -> {
                avatar = null;
                MessagesController.getInstance(currentAccount).changeChatAvatar(chatId, null, null, null, 0, null, null, null, null);
                showAvatarProgress(false, true);
                avatarImage.setImage(null, null, avatarDrawable, currentChat);
                cameraDrawable.setCurrentFrame(0);
                setAvatarCell.imageView.playAnimation();
            }, dialogInterface -> {
                if (!imageUpdater.isUploadingImage()) {
                    cameraDrawable.setCustomEndFrame(86);
                    setAvatarCell.imageView.playAnimation();
                } else {
                    cameraDrawable.setCurrentFrame(0, false);
                }
            });
            cameraDrawable.setCurrentFrame(0);
            cameraDrawable.setCustomEndFrame(43);
            setAvatarCell.imageView.playAnimation();
        });
        settingsContainer.addView(setAvatarCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    descriptionTextView = new EditTextBoldCursor(context);
    descriptionTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    descriptionTextView.setHintTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteHintText));
    descriptionTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    descriptionTextView.setPadding(0, 0, 0, AndroidUtilities.dp(6));
    descriptionTextView.setBackgroundDrawable(null);
    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);
    descriptionTextView.setEnabled(ChatObject.canChangeChatInfo(currentChat));
    descriptionTextView.setFocusable(descriptionTextView.isEnabled());
    inputFilters = new InputFilter[1];
    inputFilters[0] = new InputFilter.LengthFilter(255);
    descriptionTextView.setFilters(inputFilters);
    descriptionTextView.setHint(LocaleController.getString("DescriptionOptionalPlaceholder", R.string.DescriptionOptionalPlaceholder));
    descriptionTextView.setCursorColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
    descriptionTextView.setCursorSize(AndroidUtilities.dp(20));
    descriptionTextView.setCursorWidth(1.5f);
    if (descriptionTextView.isEnabled()) {
        settingsContainer.addView(descriptionTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 23, 15, 23, 9));
    } else {
        settingsContainer.addView(descriptionTextView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, 23, 12, 23, 6));
    }
    descriptionTextView.setOnEditorActionListener((textView, i, 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) {
        }
    });
    settingsTopSectionCell = new ShadowSectionCell(context);
    linearLayout1.addView(settingsTopSectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    typeEditContainer = new LinearLayout(context);
    typeEditContainer.setOrientation(LinearLayout.VERTICAL);
    typeEditContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout1.addView(typeEditContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    if (currentChat.megagroup && (info == null || info.can_set_location)) {
        locationCell = new TextDetailCell(context);
        locationCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        typeEditContainer.addView(locationCell, LayoutHelper.createLinear(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        locationCell.setOnClickListener(v -> {
            if (!AndroidUtilities.isGoogleMapsInstalled(ChatEditActivity.this)) {
                return;
            }
            LocationActivity fragment = new LocationActivity(LocationActivity.LOCATION_TYPE_GROUP);
            fragment.setDialogId(-chatId);
            if (info != null && info.location instanceof TLRPC.TL_channelLocation) {
                fragment.setInitialLocation((TLRPC.TL_channelLocation) info.location);
            }
            fragment.setDelegate((location, live, notify, scheduleDate) -> {
                TLRPC.TL_channelLocation channelLocation = new TLRPC.TL_channelLocation();
                channelLocation.address = location.address;
                channelLocation.geo_point = location.geo;
                info.location = channelLocation;
                info.flags |= 32768;
                updateFields(false);
                getMessagesController().loadFullChat(chatId, 0, true);
            });
            presentFragment(fragment);
        });
    }
    if (currentChat.creator && (info == null || info.can_set_username)) {
        typeCell = new TextDetailCell(context);
        typeCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        typeEditContainer.addView(typeCell, LayoutHelper.createLinear(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        typeCell.setOnClickListener(v -> {
            ChatEditTypeActivity fragment = new ChatEditTypeActivity(chatId, locationCell != null && locationCell.getVisibility() == View.VISIBLE);
            fragment.setInfo(info);
            presentFragment(fragment);
        });
    }
    if (ChatObject.isChannel(currentChat) && (isChannel && ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_CHANGE_INFO) || !isChannel && ChatObject.canUserDoAdminAction(currentChat, ChatObject.ACTION_PIN))) {
        linkedCell = new TextDetailCell(context);
        linkedCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        typeEditContainer.addView(linkedCell, LayoutHelper.createLinear(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        linkedCell.setOnClickListener(v -> {
            ChatLinkActivity fragment = new ChatLinkActivity(chatId);
            fragment.setInfo(info);
            presentFragment(fragment);
        });
    }
    if (!isChannel && ChatObject.canBlockUsers(currentChat) && (ChatObject.isChannel(currentChat) || currentChat.creator)) {
        historyCell = new TextDetailCell(context);
        historyCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        typeEditContainer.addView(historyCell, LayoutHelper.createLinear(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        historyCell.setOnClickListener(v -> {
            BottomSheet.Builder builder = new BottomSheet.Builder(context);
            builder.setApplyTopPadding(false);
            LinearLayout linearLayout = new LinearLayout(context);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            HeaderCell headerCell = new HeaderCell(context, Theme.key_dialogTextBlue2, 23, 15, false);
            headerCell.setHeight(47);
            headerCell.setText(LocaleController.getString("ChatHistory", R.string.ChatHistory));
            linearLayout.addView(headerCell);
            LinearLayout linearLayoutInviteContainer = new LinearLayout(context);
            linearLayoutInviteContainer.setOrientation(LinearLayout.VERTICAL);
            linearLayout.addView(linearLayoutInviteContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
            RadioButtonCell[] buttons = new RadioButtonCell[2];
            for (int a = 0; a < 2; a++) {
                buttons[a] = new RadioButtonCell(context, true);
                buttons[a].setTag(a);
                buttons[a].setBackgroundDrawable(Theme.getSelectorDrawable(false));
                if (a == 0) {
                    buttons[a].setTextAndValue(LocaleController.getString("ChatHistoryVisible", R.string.ChatHistoryVisible), LocaleController.getString("ChatHistoryVisibleInfo", R.string.ChatHistoryVisibleInfo), true, !historyHidden);
                } else {
                    if (ChatObject.isChannel(currentChat)) {
                        buttons[a].setTextAndValue(LocaleController.getString("ChatHistoryHidden", R.string.ChatHistoryHidden), LocaleController.getString("ChatHistoryHiddenInfo", R.string.ChatHistoryHiddenInfo), false, historyHidden);
                    } else {
                        buttons[a].setTextAndValue(LocaleController.getString("ChatHistoryHidden", R.string.ChatHistoryHidden), LocaleController.getString("ChatHistoryHiddenInfo2", R.string.ChatHistoryHiddenInfo2), false, historyHidden);
                    }
                }
                linearLayoutInviteContainer.addView(buttons[a], LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
                buttons[a].setOnClickListener(v2 -> {
                    Integer tag = (Integer) v2.getTag();
                    buttons[0].setChecked(tag == 0, true);
                    buttons[1].setChecked(tag == 1, true);
                    historyHidden = tag == 1;
                    builder.getDismissRunnable().run();
                    updateFields(true);
                });
            }
            builder.setCustomView(linearLayout);
            showDialog(builder.create());
        });
    }
    if (isChannel) {
        signCell = new TextCheckCell(context);
        signCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        signCell.setTextAndValueAndCheck(LocaleController.getString("ChannelSignMessages", R.string.ChannelSignMessages), LocaleController.getString("ChannelSignMessagesInfo", R.string.ChannelSignMessagesInfo), signMessages, true, false);
        typeEditContainer.addView(signCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        signCell.setOnClickListener(v -> {
            signMessages = !signMessages;
            ((TextCheckCell) v).setChecked(signMessages);
        });
    }
    ActionBarMenu menu = actionBar.createMenu();
    if (ChatObject.canChangeChatInfo(currentChat) || signCell != null || historyCell != null) {
        doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
        doneButton.setContentDescription(LocaleController.getString("Done", R.string.Done));
    }
    if (locationCell != null || signCell != null || historyCell != null || typeCell != null || linkedCell != null) {
        settingsSectionCell = new ShadowSectionCell(context);
        linearLayout1.addView(settingsSectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    infoContainer = new LinearLayout(context);
    infoContainer.setOrientation(LinearLayout.VERTICAL);
    infoContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout1.addView(infoContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    blockCell = new TextCell(context);
    blockCell.setBackground(Theme.getSelectorDrawable(false));
    blockCell.setVisibility(ChatObject.isChannel(currentChat) || currentChat.creator || ChatObject.hasAdminRights(currentChat) && ChatObject.canChangeChatInfo(currentChat) ? View.VISIBLE : View.GONE);
    blockCell.setOnClickListener(v -> {
        Bundle args = new Bundle();
        args.putLong("chat_id", chatId);
        args.putInt("type", !isChannel && !currentChat.gigagroup ? ChatUsersActivity.TYPE_KICKED : ChatUsersActivity.TYPE_BANNED);
        ChatUsersActivity fragment = new ChatUsersActivity(args);
        fragment.setInfo(info);
        presentFragment(fragment);
    });
    inviteLinksCell = new TextCell(context);
    inviteLinksCell.setBackground(Theme.getSelectorDrawable(false));
    inviteLinksCell.setOnClickListener(v -> {
        ManageLinksActivity fragment = new ManageLinksActivity(chatId, 0, 0);
        fragment.setInfo(info, info.exported_invite);
        presentFragment(fragment);
    });
    reactionsCell = new TextCell(context);
    reactionsCell.setBackground(Theme.getSelectorDrawable(false));
    reactionsCell.setOnClickListener(v -> {
        Bundle args = new Bundle();
        args.putLong(ChatReactionsEditActivity.KEY_CHAT_ID, chatId);
        ChatReactionsEditActivity reactionsEditActivity = new ChatReactionsEditActivity(args);
        reactionsEditActivity.setInfo(info);
        presentFragment(reactionsEditActivity);
    });
    adminCell = new TextCell(context);
    adminCell.setBackground(Theme.getSelectorDrawable(false));
    adminCell.setOnClickListener(v -> {
        Bundle args = new Bundle();
        args.putLong("chat_id", chatId);
        args.putInt("type", ChatUsersActivity.TYPE_ADMIN);
        ChatUsersActivity fragment = new ChatUsersActivity(args);
        fragment.setInfo(info);
        presentFragment(fragment);
    });
    membersCell = new TextCell(context);
    membersCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
    membersCell.setOnClickListener(v -> {
        Bundle args = new Bundle();
        args.putLong("chat_id", chatId);
        args.putInt("type", ChatUsersActivity.TYPE_USERS);
        ChatUsersActivity fragment = new ChatUsersActivity(args);
        fragment.setInfo(info);
        presentFragment(fragment);
    });
    if (!ChatObject.isChannelAndNotMegaGroup(currentChat)) {
        memberRequestsCell = new TextCell(context);
        memberRequestsCell.setBackground(Theme.getSelectorDrawable(false));
        memberRequestsCell.setOnClickListener(v -> {
            MemberRequestsActivity activity = new MemberRequestsActivity(chatId);
            presentFragment(activity);
        });
    }
    if (ChatObject.isChannel(currentChat) || currentChat.gigagroup) {
        logCell = new TextCell(context);
        logCell.setTextAndIcon(LocaleController.getString("EventLog", R.string.EventLog), R.drawable.group_log, false);
        logCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        logCell.setOnClickListener(v -> presentFragment(new ChannelAdminLogActivity(currentChat)));
    }
    infoContainer.addView(reactionsCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    if (!isChannel && !currentChat.gigagroup) {
        infoContainer.addView(blockCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    if (!isChannel) {
        infoContainer.addView(inviteLinksCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    infoContainer.addView(adminCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    infoContainer.addView(membersCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    if (memberRequestsCell != null && info != null && info.requests_pending > 0) {
        infoContainer.addView(memberRequestsCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    if (isChannel) {
        infoContainer.addView(inviteLinksCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    if (isChannel || currentChat.gigagroup) {
        infoContainer.addView(blockCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    if (logCell != null) {
        infoContainer.addView(logCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    infoSectionCell = new ShadowSectionCell(context);
    linearLayout1.addView(infoSectionCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    if (!ChatObject.hasAdminRights(currentChat)) {
        infoContainer.setVisibility(View.GONE);
        settingsTopSectionCell.setVisibility(View.GONE);
    }
    if (!isChannel && info != null && info.can_set_stickers) {
        stickersContainer = new FrameLayout(context);
        stickersContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
        linearLayout1.addView(stickersContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        stickersCell = new TextSettingsCell(context);
        stickersCell.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        stickersCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        stickersContainer.addView(stickersCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        stickersCell.setOnClickListener(v -> {
            GroupStickersActivity groupStickersActivity = new GroupStickersActivity(currentChat.id);
            groupStickersActivity.setInfo(info);
            presentFragment(groupStickersActivity);
        });
        stickersInfoCell3 = new TextInfoPrivacyCell(context);
        stickersInfoCell3.setText(LocaleController.getString("GroupStickersInfo", R.string.GroupStickersInfo));
        linearLayout1.addView(stickersInfoCell3, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }
    if (currentChat.creator) {
        deleteContainer = new FrameLayout(context);
        deleteContainer.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
        linearLayout1.addView(deleteContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        deleteCell = new TextSettingsCell(context);
        deleteCell.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteRedText5));
        deleteCell.setBackgroundDrawable(Theme.getSelectorDrawable(false));
        if (isChannel) {
            deleteCell.setText(LocaleController.getString("ChannelDelete", R.string.ChannelDelete), false);
        } else {
            deleteCell.setText(LocaleController.getString("DeleteAndExitButton", R.string.DeleteAndExitButton), false);
        }
        deleteContainer.addView(deleteCell, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        deleteCell.setOnClickListener(v -> AlertsCreator.createClearOrDeleteDialogAlert(ChatEditActivity.this, false, true, false, currentChat, null, false, true, (param) -> {
            if (AndroidUtilities.isTablet()) {
                getNotificationCenter().postNotificationName(NotificationCenter.closeChats, -chatId);
            } else {
                getNotificationCenter().postNotificationName(NotificationCenter.closeChats);
            }
            finishFragment();
            getNotificationCenter().postNotificationName(NotificationCenter.needDeleteDialog, -currentChat.id, null, currentChat, param);
        }, null));
        deleteInfoCell = new ShadowSectionCell(context);
        deleteInfoCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
        linearLayout1.addView(deleteInfoCell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    } else {
        if (!isChannel) {
            if (stickersInfoCell3 == null) {
                infoSectionCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
            }
        }
    }
    if (stickersInfoCell3 != null) {
        if (deleteInfoCell == null) {
            stickersInfoCell3.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom, Theme.key_windowBackgroundGrayShadow));
        } else {
            stickersInfoCell3.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));
        }
    }
    undoView = new UndoView(context);
    sizeNotifierFrameLayout.addView(undoView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM | Gravity.LEFT, 8, 0, 8, 8));
    nameTextView.setText(currentChat.title);
    nameTextView.setSelection(nameTextView.length());
    if (info != null) {
        descriptionTextView.setText(info.about);
    }
    setAvatar();
    updateFields(true);
    return fragmentView;
}
Also used : ThemeDescription(org.telegram.ui.ActionBar.ThemeDescription) LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) ImageUpdater(org.telegram.ui.Components.ImageUpdater) FrameLayout(android.widget.FrameLayout) AndroidUtilities(org.telegram.messenger.AndroidUtilities) Animator(android.animation.Animator) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) RadialProgressView(org.telegram.ui.Components.RadialProgressView) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) TextCell(org.telegram.ui.Cells.TextCell) View(android.view.View) Canvas(android.graphics.Canvas) ObjectAnimator(android.animation.ObjectAnimator) ImageLocation(org.telegram.messenger.ImageLocation) UndoView(org.telegram.ui.Components.UndoView) InputType(android.text.InputType) BaseFragment(org.telegram.ui.ActionBar.BaseFragment) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) ViewGroup(android.view.ViewGroup) NotificationCenter(org.telegram.messenger.NotificationCenter) RadioButtonCell(org.telegram.ui.Cells.RadioButtonCell) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Paint(android.graphics.Paint) InputFilter(android.text.InputFilter) EditorInfo(android.view.inputmethod.EditorInfo) TextWatcher(android.text.TextWatcher) Context(android.content.Context) Theme(org.telegram.ui.ActionBar.Theme) TextDetailCell(org.telegram.ui.Cells.TextDetailCell) Dialog(android.app.Dialog) Intent(android.content.Intent) LocaleController(org.telegram.messenger.LocaleController) HeaderCell(org.telegram.ui.Cells.HeaderCell) AlertsCreator(org.telegram.ui.Components.AlertsCreator) Editable(android.text.Editable) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) ArrayList(java.util.ArrayList) TLRPC(org.telegram.tgnet.TLRPC) ActionBar(org.telegram.ui.ActionBar.ActionBar) EditTextEmoji(org.telegram.ui.Components.EditTextEmoji) AnimatorSet(android.animation.AnimatorSet) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) MessageObject(org.telegram.messenger.MessageObject) Build(android.os.Build) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) R(org.telegram.messenger.R) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) BackupImageView(org.telegram.ui.Components.BackupImageView) TextUtils(android.text.TextUtils) LayoutHelper(org.telegram.ui.Components.LayoutHelper) FileLog(org.telegram.messenger.FileLog) MessagesController(org.telegram.messenger.MessagesController) Gravity(android.view.Gravity) TypedValue(android.util.TypedValue) ScrollView(android.widget.ScrollView) MessagesStorage(org.telegram.messenger.MessagesStorage) TextCheckCell(org.telegram.ui.Cells.TextCheckCell) Vibrator(android.os.Vibrator) ChatObject(org.telegram.messenger.ChatObject) AlertDialog(org.telegram.ui.ActionBar.AlertDialog) Collections(java.util.Collections) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) TextCheckCell(org.telegram.ui.Cells.TextCheckCell) HeaderCell(org.telegram.ui.Cells.HeaderCell) TLRPC(org.telegram.tgnet.TLRPC) BackupImageView(org.telegram.ui.Components.BackupImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) InputFilter(android.text.InputFilter) RadialProgressView(org.telegram.ui.Components.RadialProgressView) ShadowSectionCell(org.telegram.ui.Cells.ShadowSectionCell) Canvas(android.graphics.Canvas) TextInfoPrivacyCell(org.telegram.ui.Cells.TextInfoPrivacyCell) Paint(android.graphics.Paint) ActionBarMenu(org.telegram.ui.ActionBar.ActionBarMenu) BottomSheet(org.telegram.ui.ActionBar.BottomSheet) RadioButtonCell(org.telegram.ui.Cells.RadioButtonCell) ImageLocation(org.telegram.messenger.ImageLocation) TextCell(org.telegram.ui.Cells.TextCell) UndoView(org.telegram.ui.Components.UndoView) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) EditTextBoldCursor(org.telegram.ui.Components.EditTextBoldCursor) TextDetailCell(org.telegram.ui.Cells.TextDetailCell) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) Bundle(android.os.Bundle) RadialProgressView(org.telegram.ui.Components.RadialProgressView) View(android.view.View) UndoView(org.telegram.ui.Components.UndoView) BackupImageView(org.telegram.ui.Components.BackupImageView) ScrollView(android.widget.ScrollView) Paint(android.graphics.Paint) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) ScrollView(android.widget.ScrollView) FrameLayout(android.widget.FrameLayout) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) EditTextEmoji(org.telegram.ui.Components.EditTextEmoji) LinearLayout(android.widget.LinearLayout)

Example 10 with TextSettingsCell

use of org.telegram.ui.Cells.TextSettingsCell in project Telegram-FOSS by Telegram-FOSS-Team.

the class GroupCreateFinalActivity method createView.

@Override
public View createView(Context context) {
    if (editText != null) {
        editText.onDestroy();
    }
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("NewGroup", R.string.NewGroup));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });
    SizeNotifierFrameLayout sizeNotifierFrameLayout = new SizeNotifierFrameLayout(context) {

        private boolean ignoreLayout;

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            setMeasuredDimension(widthSize, heightSize);
            heightSize -= getPaddingTop();
            measureChildWithMargins(actionBar, widthMeasureSpec, 0, heightMeasureSpec, 0);
            int keyboardSize = measureKeyboardHeight();
            if (keyboardSize > AndroidUtilities.dp(20)) {
                ignoreLayout = true;
                editText.hideEmojiView();
                ignoreLayout = false;
            }
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if (child == null || child.getVisibility() == GONE || child == actionBar) {
                    continue;
                }
                if (editText != null && editText.isPopupView(child)) {
                    if (AndroidUtilities.isInMultiwindow || AndroidUtilities.isTablet()) {
                        if (AndroidUtilities.isTablet()) {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(AndroidUtilities.isTablet() ? 200 : 320), heightSize - AndroidUtilities.statusBarHeight + getPaddingTop()), MeasureSpec.EXACTLY));
                        } else {
                            child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(heightSize - AndroidUtilities.statusBarHeight + getPaddingTop(), MeasureSpec.EXACTLY));
                        }
                    } else {
                        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(child.getLayoutParams().height, MeasureSpec.EXACTLY));
                    }
                } else {
                    measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                }
            }
        }

        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            final int count = getChildCount();
            int keyboardSize = measureKeyboardHeight();
            int paddingBottom = keyboardSize <= AndroidUtilities.dp(20) && !AndroidUtilities.isInMultiwindow && !AndroidUtilities.isTablet() ? editText.getEmojiPadding() : 0;
            setBottomClip(paddingBottom);
            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child.getVisibility() == GONE) {
                    continue;
                }
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();
                int childLeft;
                int childTop;
                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = Gravity.TOP | Gravity.LEFT;
                }
                final int absoluteGravity = gravity & Gravity.HORIZONTAL_GRAVITY_MASK;
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
                switch(absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = (r - l - width) / 2 + lp.leftMargin - lp.rightMargin;
                        break;
                    case Gravity.RIGHT:
                        childLeft = r - width - lp.rightMargin;
                        break;
                    case Gravity.LEFT:
                    default:
                        childLeft = lp.leftMargin;
                }
                switch(verticalGravity) {
                    case Gravity.TOP:
                        childTop = lp.topMargin + getPaddingTop();
                        break;
                    case Gravity.CENTER_VERTICAL:
                        childTop = ((b - paddingBottom) - t - height) / 2 + lp.topMargin - lp.bottomMargin;
                        break;
                    case Gravity.BOTTOM:
                        childTop = ((b - paddingBottom) - t) - height - lp.bottomMargin;
                        break;
                    default:
                        childTop = lp.topMargin;
                }
                if (editText != null && editText.isPopupView(child)) {
                    if (AndroidUtilities.isTablet()) {
                        childTop = getMeasuredHeight() - child.getMeasuredHeight();
                    } else {
                        childTop = getMeasuredHeight() + keyboardSize - child.getMeasuredHeight();
                    }
                }
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
            notifyHeightChanged();
        }

        @Override
        public void requestLayout() {
            if (ignoreLayout) {
                return;
            }
            super.requestLayout();
        }
    };
    fragmentView = sizeNotifierFrameLayout;
    fragmentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    fragmentView.setOnTouchListener((v, event) -> true);
    shadowDrawable = context.getResources().getDrawable(R.drawable.greydivider_top).mutate();
    LinearLayout linearLayout = new LinearLayout(context) {

        @Override
        protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
            boolean result = super.drawChild(canvas, child, drawingTime);
            if (child == listView && shadowDrawable != null) {
                int y = editTextContainer.getMeasuredHeight();
                shadowDrawable.setBounds(0, y, getMeasuredWidth(), y + shadowDrawable.getIntrinsicHeight());
                shadowDrawable.draw(canvas);
            }
            return result;
        }
    };
    linearLayout.setOrientation(LinearLayout.VERTICAL);
    sizeNotifierFrameLayout.addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    editTextContainer = new FrameLayout(context);
    linearLayout.addView(editTextContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    avatarImage = new BackupImageView(context) {

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

        @Override
        public void invalidate(int l, int t, int r, int b) {
            if (avatarOverlay != null) {
                avatarOverlay.invalidate();
            }
            super.invalidate(l, t, r, b);
        }
    };
    avatarImage.setRoundRadius(AndroidUtilities.dp(32));
    avatarDrawable.setInfo(5, null, null);
    avatarImage.setImageDrawable(avatarDrawable);
    avatarImage.setContentDescription(LocaleController.getString("ChoosePhoto", R.string.ChoosePhoto));
    editTextContainer.addView(avatarImage, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 16, LocaleController.isRTL ? 16 : 0, 16));
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(0x55000000);
    avatarOverlay = new View(context) {

        @Override
        protected void onDraw(Canvas canvas) {
            if (avatarImage != null && avatarProgressView.getVisibility() == VISIBLE) {
                paint.setAlpha((int) (0x55 * avatarImage.getImageReceiver().getCurrentAlpha() * avatarProgressView.getAlpha()));
                canvas.drawCircle(getMeasuredWidth() / 2.0f, getMeasuredHeight() / 2.0f, getMeasuredWidth() / 2.0f, paint);
            }
        }
    };
    editTextContainer.addView(avatarOverlay, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 16, LocaleController.isRTL ? 16 : 0, 16));
    avatarOverlay.setOnClickListener(view -> {
        imageUpdater.openMenu(avatar != null, () -> {
            avatar = null;
            avatarBig = null;
            inputPhoto = null;
            inputVideo = null;
            inputVideoPath = null;
            videoTimestamp = 0;
            showAvatarProgress(false, true);
            avatarImage.setImage(null, null, avatarDrawable, null);
            avatarEditor.setAnimation(cameraDrawable);
            cameraDrawable.setCurrentFrame(0);
        }, dialog -> {
            if (!imageUpdater.isUploadingImage()) {
                cameraDrawable.setCustomEndFrame(86);
                avatarEditor.playAnimation();
            } else {
                cameraDrawable.setCurrentFrame(0, false);
            }
        });
        cameraDrawable.setCurrentFrame(0);
        cameraDrawable.setCustomEndFrame(43);
        avatarEditor.playAnimation();
    });
    cameraDrawable = new RLottieDrawable(R.raw.camera, "" + R.raw.camera, AndroidUtilities.dp(60), AndroidUtilities.dp(60), false, null);
    avatarEditor = new RLottieImageView(context) {

        @Override
        public void invalidate(int l, int t, int r, int b) {
            super.invalidate(l, t, r, b);
            avatarOverlay.invalidate();
        }

        @Override
        public void invalidate() {
            super.invalidate();
            avatarOverlay.invalidate();
        }
    };
    avatarEditor.setScaleType(ImageView.ScaleType.CENTER);
    avatarEditor.setAnimation(cameraDrawable);
    avatarEditor.setEnabled(false);
    avatarEditor.setClickable(false);
    avatarEditor.setPadding(AndroidUtilities.dp(2), 0, 0, AndroidUtilities.dp(1));
    editTextContainer.addView(avatarEditor, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 16, LocaleController.isRTL ? 16 : 0, 16));
    avatarProgressView = new RadialProgressView(context) {

        @Override
        public void setAlpha(float alpha) {
            super.setAlpha(alpha);
            avatarOverlay.invalidate();
        }
    };
    avatarProgressView.setSize(AndroidUtilities.dp(30));
    avatarProgressView.setProgressColor(0xffffffff);
    avatarProgressView.setNoProgress(false);
    editTextContainer.addView(avatarProgressView, LayoutHelper.createFrame(64, 64, Gravity.TOP | (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT), LocaleController.isRTL ? 0 : 16, 16, LocaleController.isRTL ? 16 : 0, 16));
    showAvatarProgress(false, false);
    editText = new EditTextEmoji(context, sizeNotifierFrameLayout, this, EditTextEmoji.STYLE_FRAGMENT);
    editText.setHint(chatType == ChatObject.CHAT_TYPE_CHAT || chatType == ChatObject.CHAT_TYPE_MEGAGROUP ? LocaleController.getString("EnterGroupNamePlaceholder", R.string.EnterGroupNamePlaceholder) : LocaleController.getString("EnterListName", R.string.EnterListName));
    if (nameToSet != null) {
        editText.setText(nameToSet);
        nameToSet = null;
    }
    InputFilter[] inputFilters = new InputFilter[1];
    inputFilters[0] = new InputFilter.LengthFilter(100);
    editText.setFilters(inputFilters);
    editTextContainer.addView(editText, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER_VERTICAL, LocaleController.isRTL ? 5 : 96, 0, LocaleController.isRTL ? 96 : 5, 0));
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
    listView = new RecyclerListView(context);
    listView.setAdapter(adapter = new GroupCreateAdapter(context));
    listView.setLayoutManager(linearLayoutManager);
    listView.setVerticalScrollBarEnabled(false);
    listView.setVerticalScrollbarPosition(LocaleController.isRTL ? View.SCROLLBAR_POSITION_LEFT : View.SCROLLBAR_POSITION_RIGHT);
    GroupCreateDividerItemDecoration decoration = new GroupCreateDividerItemDecoration();
    decoration.setSkipRows(currentGroupCreateAddress != null ? 5 : 2);
    listView.addItemDecoration(decoration);
    linearLayout.addView(listView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                AndroidUtilities.hideKeyboard(editText);
            }
        }
    });
    listView.setOnItemClickListener((view, position) -> {
        if (view instanceof TextSettingsCell) {
            if (!AndroidUtilities.isGoogleMapsInstalled(GroupCreateFinalActivity.this)) {
                return;
            }
            LocationActivity fragment = new LocationActivity(LocationActivity.LOCATION_TYPE_GROUP);
            fragment.setDialogId(0);
            fragment.setDelegate((location, live, notify, scheduleDate) -> {
                currentGroupCreateLocation.setLatitude(location.geo.lat);
                currentGroupCreateLocation.setLongitude(location.geo._long);
                currentGroupCreateAddress = location.address;
            });
            presentFragment(fragment);
        }
    });
    floatingButtonContainer = new FrameLayout(context);
    Drawable drawable = Theme.createSimpleSelectorCircleDrawable(AndroidUtilities.dp(56), Theme.getColor(Theme.key_chats_actionBackground), Theme.getColor(Theme.key_chats_actionPressedBackground));
    if (Build.VERSION.SDK_INT < 21) {
        Drawable shadowDrawable = context.getResources().getDrawable(R.drawable.floating_shadow).mutate();
        shadowDrawable.setColorFilter(new PorterDuffColorFilter(0xff000000, PorterDuff.Mode.MULTIPLY));
        CombinedDrawable combinedDrawable = new CombinedDrawable(shadowDrawable, drawable, 0, 0);
        combinedDrawable.setIconSize(AndroidUtilities.dp(56), AndroidUtilities.dp(56));
        drawable = combinedDrawable;
    }
    floatingButtonContainer.setBackgroundDrawable(drawable);
    if (Build.VERSION.SDK_INT >= 21) {
        StateListAnimator animator = new StateListAnimator();
        animator.addState(new int[] { android.R.attr.state_pressed }, ObjectAnimator.ofFloat(floatingButtonIcon, "translationZ", AndroidUtilities.dp(2), AndroidUtilities.dp(4)).setDuration(200));
        animator.addState(new int[] {}, ObjectAnimator.ofFloat(floatingButtonIcon, "translationZ", AndroidUtilities.dp(4), AndroidUtilities.dp(2)).setDuration(200));
        floatingButtonContainer.setStateListAnimator(animator);
        floatingButtonContainer.setOutlineProvider(new ViewOutlineProvider() {

            @SuppressLint("NewApi")
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setOval(0, 0, AndroidUtilities.dp(56), AndroidUtilities.dp(56));
            }
        });
    }
    VerticalPositionAutoAnimator.attach(floatingButtonContainer);
    sizeNotifierFrameLayout.addView(floatingButtonContainer, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.BOTTOM, LocaleController.isRTL ? 14 : 0, 0, LocaleController.isRTL ? 0 : 14, 14));
    floatingButtonContainer.setOnClickListener(view -> {
        if (donePressed) {
            return;
        }
        if (editText.length() == 0) {
            Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
            if (v != null) {
                v.vibrate(200);
            }
            AndroidUtilities.shakeView(editText, 2, 0);
            return;
        }
        donePressed = true;
        AndroidUtilities.hideKeyboard(editText);
        editText.setEnabled(false);
        if (imageUpdater.isUploadingImage()) {
            createAfterUpload = true;
        } else {
            showEditDoneProgress(true);
            reqId = getMessagesController().createChat(editText.getText().toString(), selectedContacts, null, chatType, forImport, currentGroupCreateLocation, currentGroupCreateAddress, GroupCreateFinalActivity.this);
        }
    });
    floatingButtonIcon = new ImageView(context);
    floatingButtonIcon.setScaleType(ImageView.ScaleType.CENTER);
    floatingButtonIcon.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_chats_actionIcon), PorterDuff.Mode.MULTIPLY));
    floatingButtonIcon.setImageResource(R.drawable.checkbig);
    floatingButtonIcon.setPadding(0, AndroidUtilities.dp(2), 0, 0);
    floatingButtonContainer.setContentDescription(LocaleController.getString("Done", R.string.Done));
    floatingButtonContainer.addView(floatingButtonIcon, LayoutHelper.createFrame(Build.VERSION.SDK_INT >= 21 ? 56 : 60, Build.VERSION.SDK_INT >= 21 ? 56 : 60));
    progressView = new ContextProgressView(context, 1);
    progressView.setAlpha(0.0f);
    progressView.setScaleX(0.1f);
    progressView.setScaleY(0.1f);
    progressView.setVisibility(View.INVISIBLE);
    floatingButtonContainer.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    return fragmentView;
}
Also used : ContextProgressView(org.telegram.ui.Components.ContextProgressView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) StateListAnimator(android.animation.StateListAnimator) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) PorterDuffColorFilter(android.graphics.PorterDuffColorFilter) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) RecyclerListView(org.telegram.ui.Components.RecyclerListView) BackupImageView(org.telegram.ui.Components.BackupImageView) ImageView(android.widget.ImageView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) BackupImageView(org.telegram.ui.Components.BackupImageView) ActionBar(org.telegram.ui.ActionBar.ActionBar) InputFilter(android.text.InputFilter) RadialProgressView(org.telegram.ui.Components.RadialProgressView) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) ViewGroup(android.view.ViewGroup) Canvas(android.graphics.Canvas) ColorDrawable(android.graphics.drawable.ColorDrawable) Drawable(android.graphics.drawable.Drawable) AvatarDrawable(org.telegram.ui.Components.AvatarDrawable) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) RLottieDrawable(org.telegram.ui.Components.RLottieDrawable) Outline(android.graphics.Outline) Paint(android.graphics.Paint) ImageView(android.widget.ImageView) RadialProgressView(org.telegram.ui.Components.RadialProgressView) View(android.view.View) RecyclerView(androidx.recyclerview.widget.RecyclerView) ContextProgressView(org.telegram.ui.Components.ContextProgressView) RLottieImageView(org.telegram.ui.Components.RLottieImageView) BackupImageView(org.telegram.ui.Components.BackupImageView) RecyclerListView(org.telegram.ui.Components.RecyclerListView) ViewOutlineProvider(android.view.ViewOutlineProvider) Paint(android.graphics.Paint) SuppressLint(android.annotation.SuppressLint) GroupCreateDividerItemDecoration(org.telegram.ui.Components.GroupCreateDividerItemDecoration) TextSettingsCell(org.telegram.ui.Cells.TextSettingsCell) FrameLayout(android.widget.FrameLayout) SizeNotifierFrameLayout(org.telegram.ui.Components.SizeNotifierFrameLayout) CombinedDrawable(org.telegram.ui.Components.CombinedDrawable) SuppressLint(android.annotation.SuppressLint) RecyclerView(androidx.recyclerview.widget.RecyclerView) Vibrator(android.os.Vibrator) EditTextEmoji(org.telegram.ui.Components.EditTextEmoji) LinearLayout(android.widget.LinearLayout)

Aggregations

TextSettingsCell (org.telegram.ui.Cells.TextSettingsCell)16 View (android.view.View)14 TextView (android.widget.TextView)12 TextInfoPrivacyCell (org.telegram.ui.Cells.TextInfoPrivacyCell)12 FrameLayout (android.widget.FrameLayout)11 HeaderCell (org.telegram.ui.Cells.HeaderCell)11 LinearLayout (android.widget.LinearLayout)10 ArrayList (java.util.ArrayList)10 Canvas (android.graphics.Canvas)9 Editable (android.text.Editable)9 TextWatcher (android.text.TextWatcher)9 ViewGroup (android.view.ViewGroup)9 ActionBar (org.telegram.ui.ActionBar.ActionBar)9 EditTextBoldCursor (org.telegram.ui.Components.EditTextBoldCursor)9 SuppressLint (android.annotation.SuppressLint)8 Paint (android.graphics.Paint)8 InputFilter (android.text.InputFilter)8 SpannableStringBuilder (android.text.SpannableStringBuilder)8 TextPaint (android.text.TextPaint)8 ScrollView (android.widget.ScrollView)8