Example usage for android.text SpannableStringBuilder setSpan

List of usage examples for android.text SpannableStringBuilder setSpan

Introduction

In this page you can find the example usage for android.text SpannableStringBuilder setSpan.

Prototype

public void setSpan(Object what, int start, int end, int flags) 

Source Link

Document

Mark the specified range of text with the specified object.

Usage

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

private CharSequence getText(TLRPC.RichText parentRichText, TLRPC.RichText richText,
        TLRPC.PageBlock parentBlock) {//from w  w w .j ava 2s  .co  m
    if (richText instanceof TLRPC.TL_textFixed) {
        return getText(parentRichText, ((TLRPC.TL_textFixed) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textItalic) {
        return getText(parentRichText, ((TLRPC.TL_textItalic) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textBold) {
        return getText(parentRichText, ((TLRPC.TL_textBold) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textUnderline) {
        return getText(parentRichText, ((TLRPC.TL_textUnderline) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textStrike) {
        return getText(parentRichText, ((TLRPC.TL_textStrike) richText).text, parentBlock);
    } else if (richText instanceof TLRPC.TL_textEmail) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
                getText(parentRichText, ((TLRPC.TL_textEmail) richText).text, parentBlock));
        MetricAffectingSpan innerSpans[] = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(),
                MetricAffectingSpan.class);
        spannableStringBuilder.setSpan(
                new TextPaintUrlSpan(innerSpans == null || innerSpans.length == 0
                        ? getTextPaint(parentRichText, richText, parentBlock)
                        : null, getUrl(richText)),
                0, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableStringBuilder;
    } else if (richText instanceof TLRPC.TL_textUrl) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(
                getText(parentRichText, ((TLRPC.TL_textUrl) richText).text, parentBlock));
        MetricAffectingSpan innerSpans[] = spannableStringBuilder.getSpans(0, spannableStringBuilder.length(),
                MetricAffectingSpan.class);
        spannableStringBuilder.setSpan(
                new TextPaintUrlSpan(innerSpans == null || innerSpans.length == 0
                        ? getTextPaint(parentRichText, richText, parentBlock)
                        : null, getUrl(richText)),
                0, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableStringBuilder;
    } else if (richText instanceof TLRPC.TL_textPlain) {
        return ((TLRPC.TL_textPlain) richText).text;
    } else if (richText instanceof TLRPC.TL_textEmpty) {
        return "";
    } else if (richText instanceof TLRPC.TL_textConcat) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        int count = richText.texts.size();
        for (int a = 0; a < count; a++) {
            TLRPC.RichText innerRichText = richText.texts.get(a);
            CharSequence innerText = getText(parentRichText, innerRichText, parentBlock);
            int flags = getTextFlags(innerRichText);
            int startLength = spannableStringBuilder.length();
            spannableStringBuilder.append(innerText);
            if (flags != 0 && !(innerText instanceof SpannableStringBuilder)) {
                if ((flags & TEXT_FLAG_URL) != 0) {
                    String url = getUrl(innerRichText);
                    if (url == null) {
                        url = getUrl(parentRichText);
                    }
                    spannableStringBuilder.setSpan(
                            new TextPaintUrlSpan(getTextPaint(parentRichText, innerRichText, parentBlock), url),
                            startLength, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                } else {
                    spannableStringBuilder.setSpan(
                            new TextPaintSpan(getTextPaint(parentRichText, innerRichText, parentBlock)),
                            startLength, spannableStringBuilder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
        }
        return spannableStringBuilder;
    }
    return "not supported " + richText;
}

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

private void createAddressInterface(Context context) {
    languageMap = new HashMap<>();
    try {/*w  w  w  .  j a  v a2 s  .  c o  m*/
        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) {
        if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeRentalAgreement) {
            actionBar.setTitle(LocaleController.getString("ActionBotDocumentRentalAgreement",
                    R.string.ActionBotDocumentRentalAgreement));
        } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeBankStatement) {
            actionBar.setTitle(LocaleController.getString("ActionBotDocumentBankStatement",
                    R.string.ActionBotDocumentBankStatement));
        } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeUtilityBill) {
            actionBar.setTitle(LocaleController.getString("ActionBotDocumentUtilityBill",
                    R.string.ActionBotDocumentUtilityBill));
        } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypePassportRegistration) {
            actionBar.setTitle(LocaleController.getString("ActionBotDocumentPassportRegistration",
                    R.string.ActionBotDocumentPassportRegistration));
        } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeTemporaryRegistration) {
            actionBar.setTitle(LocaleController.getString("ActionBotDocumentTemporaryRegistration",
                    R.string.ActionBotDocumentTemporaryRegistration));
        }

        headerCell = new HeaderCell(context);
        headerCell.setText(LocaleController.getString("PassportDocuments", R.string.PassportDocuments));
        headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
        linearLayout2.addView(headerCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

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

        uploadDocumentCell = new TextSettingsCell(context);
        uploadDocumentCell.setBackgroundDrawable(Theme.getSelectorDrawable(true));
        linearLayout2.addView(uploadDocumentCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        uploadDocumentCell.setOnClickListener(v -> {
            uploadingFileType = UPLOADING_TYPE_DOCUMENTS;
            openAttachMenu();
        });

        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(
                Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));

        if (currentBotId != 0) {
            noAllDocumentsErrorText = LocaleController.getString("PassportAddAddressUploadInfo",
                    R.string.PassportAddAddressUploadInfo);
        } else {
            if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeRentalAgreement) {
                noAllDocumentsErrorText = LocaleController.getString("PassportAddAgreementInfo",
                        R.string.PassportAddAgreementInfo);
            } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeUtilityBill) {
                noAllDocumentsErrorText = LocaleController.getString("PassportAddBillInfo",
                        R.string.PassportAddBillInfo);
            } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypePassportRegistration) {
                noAllDocumentsErrorText = LocaleController.getString("PassportAddPassportRegistrationInfo",
                        R.string.PassportAddPassportRegistrationInfo);
            } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeTemporaryRegistration) {
                noAllDocumentsErrorText = LocaleController.getString("PassportAddTemporaryRegistrationInfo",
                        R.string.PassportAddTemporaryRegistrationInfo);
            } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeBankStatement) {
                noAllDocumentsErrorText = LocaleController.getString("PassportAddBankInfo",
                        R.string.PassportAddBankInfo);
            } else {
                noAllDocumentsErrorText = "";
            }
        }

        CharSequence text = noAllDocumentsErrorText;
        if (documentsErrors != null) {
            String errorText;
            if ((errorText = documentsErrors.get("files_all")) != null) {
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(errorText);
                stringBuilder.append("\n\n");
                stringBuilder.append(noAllDocumentsErrorText);
                text = stringBuilder;
                stringBuilder.setSpan(
                        new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteRedText3)), 0,
                        errorText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                errorsValues.put("files_all", "");
            }
        }
        bottomCell.setText(text);
        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_secureValueTypeRentalAgreement) {
                    noAllTranslationErrorText = LocaleController.getString(
                            "PassportAddTranslationAgreementInfo",
                            R.string.PassportAddTranslationAgreementInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeUtilityBill) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddTranslationBillInfo",
                            R.string.PassportAddTranslationBillInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypePassportRegistration) {
                    noAllTranslationErrorText = LocaleController.getString(
                            "PassportAddTranslationPassportRegistrationInfo",
                            R.string.PassportAddTranslationPassportRegistrationInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeTemporaryRegistration) {
                    noAllTranslationErrorText = LocaleController.getString(
                            "PassportAddTranslationTemporaryRegistrationInfo",
                            R.string.PassportAddTranslationTemporaryRegistrationInfo);
                } else if (currentDocumentsType.type instanceof TLRPC.TL_secureValueTypeBankStatement) {
                    noAllTranslationErrorText = LocaleController.getString("PassportAddTranslationBankInfo",
                            R.string.PassportAddTranslationBankInfo);
                } else {
                    noAllTranslationErrorText = "";
                }
            }

            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 {
        actionBar.setTitle(LocaleController.getString("PassportAddress", R.string.PassportAddress));
    }

    headerCell = new HeaderCell(context);
    headerCell.setText(LocaleController.getString("PassportAddressHeader", R.string.PassportAddressHeader));
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    inputFields = new EditTextBoldCursor[FIELD_ADDRESS_COUNT];
    for (int a = 0; a < FIELD_ADDRESS_COUNT; a++) {
        final EditTextBoldCursor field = new EditTextBoldCursor(context);
        inputFields[a] = field;

        ViewGroup container = new FrameLayout(context) {

            private StaticLayout errorLayout;
            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, LayoutHelper.WRAP_CONTENT));
        container.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));

        if (a == FIELD_ADDRESS_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) {
            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].setHeaderHintColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlueHeader));
        inputFields[a].setTransformHintToHeader(true);
        inputFields[a].setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText));
        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_COUNTRY) {
            inputFields[a].setOnTouchListener((v, event) -> {
                if (getParentActivity() == null) {
                    return false;
                }
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    CountrySelectActivity fragment = new CountrySelectActivity(false);
                    fragment.setCountrySelectActivityDelegate((name, shortName) -> {
                        inputFields[FIELD_COUNTRY].setText(name);
                        currentCitizeship = shortName;
                    });
                    presentFragment(fragment);
                }
                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;
        switch (a) {
        case FIELD_STREET1:
            inputFields[a].setHintText(LocaleController.getString("PassportStreet1", R.string.PassportStreet1));
            key = "street_line1";
            break;
        case FIELD_STREET2:
            inputFields[a].setHintText(LocaleController.getString("PassportStreet2", R.string.PassportStreet2));
            key = "street_line2";
            break;
        case FIELD_CITY:
            inputFields[a].setHintText(LocaleController.getString("PassportCity", R.string.PassportCity));
            key = "city";
            break;
        case FIELD_STATE:
            inputFields[a].setHintText(LocaleController.getString("PassportState", R.string.PassportState));
            key = "state";
            break;
        case FIELD_COUNTRY:
            inputFields[a].setHintText(LocaleController.getString("PassportCountry", R.string.PassportCountry));
            key = "country_code";
            break;
        case FIELD_POSTCODE:
            inputFields[a]
                    .setHintText(LocaleController.getString("PassportPostcode", R.string.PassportPostcode));
            key = "post_code";
            break;
        default:
            continue;
        }
        setFieldValues(currentValues, inputFields[a], key);
        if (a == FIELD_POSTCODE) {
            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;
                    }
                    ignore = true;
                    boolean error = false;
                    for (int a = 0; a < s.length(); a++) {
                        char ch = s.charAt(a);
                        if (!(ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9'
                                || ch == '-' || ch == ' ')) {
                            error = true;
                            break;
                        }
                    }
                    ignore = false;
                    if (error) {
                        field.setErrorText(LocaleController.getString("PassportUseLatinOnly",
                                R.string.PassportUseLatinOnly));
                    } else {
                        checkFieldForError(field, key, s, false);
                    }
                }
            });
            InputFilter[] inputFilters = new InputFilter[1];
            inputFilters[0] = new InputFilter.LengthFilter(10);
            inputFields[a].setFilters(inputFilters);
        } 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, false);
                }
            });
        }

        inputFields[a].setSelection(inputFields[a].length());
        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, 64,
                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;
        });
    }

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

    if (documentOnly && currentDocumentsType != null) {
        headerCell.setVisibility(View.GONE);
        sectionCell.setVisibility(View.GONE);
    }

    if ((currentBotId != 0 || currentDocumentsType == null) && currentTypeValue != null && !documentOnly
            || currentDocumentsTypeValue != null) {
        if (currentDocumentsTypeValue != null) {
            addDocumentViews(currentDocumentsTypeValue.files);
            addTranslationDocumentViews(currentDocumentsTypeValue.translation);
        }
        sectionCell.setBackgroundDrawable(
                Theme.getThemedDrawable(context, R.drawable.greydivider, Theme.key_windowBackgroundGrayShadow));

        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());

        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 {
        sectionCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom,
                Theme.key_windowBackgroundGrayShadow));
        if (documentOnly && currentDocumentsType != null) {
            bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom,
                    Theme.key_windowBackgroundGrayShadow));
        }
    }
    updateUploadText(UPLOADING_TYPE_DOCUMENTS);
    updateUploadText(UPLOADING_TYPE_TRANSLATION);
}

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

@Override
public View createView(Context context) {

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

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        private boolean onIdentityDone(Runnable finishRunnable, ErrorRunnable errorRunnable) {
            if (!uploadingDocuments.isEmpty() || checkFieldsForError()) {
                return false;
            }/*from   w ww .  j  a  v  a 2s  .c o m*/
            if (allowNonLatinName) {
                allowNonLatinName = false;
                boolean error = false;
                for (int a = 0; a < nonLatinNames.length; a++) {
                    if (nonLatinNames[a]) {
                        inputFields[a].setErrorText(LocaleController.getString("PassportUseLatinOnly",
                                R.string.PassportUseLatinOnly));
                        if (!error) {
                            error = true;
                            String firstName = nonLatinNames[0]
                                    ? getTranslitString(
                                            inputExtraFields[FIELD_NATIVE_NAME].getText().toString())
                                    : inputFields[FIELD_NAME].getText().toString();
                            String middleName = nonLatinNames[1]
                                    ? getTranslitString(
                                            inputExtraFields[FIELD_NATIVE_MIDNAME].getText().toString())
                                    : inputFields[FIELD_MIDNAME].getText().toString();
                            String lastName = nonLatinNames[2]
                                    ? getTranslitString(
                                            inputExtraFields[FIELD_NATIVE_SURNAME].getText().toString())
                                    : inputFields[FIELD_SURNAME].getText().toString();

                            if (!TextUtils.isEmpty(firstName) && !TextUtils.isEmpty(middleName)
                                    && !TextUtils.isEmpty(lastName)) {
                                int num = a;
                                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                                builder.setMessage(LocaleController.formatString("PassportNameCheckAlert",
                                        R.string.PassportNameCheckAlert, firstName, middleName, lastName));
                                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                                builder.setPositiveButton(LocaleController.getString("Done", R.string.Done),
                                        (dialogInterface, i) -> {
                                            inputFields[FIELD_NAME].setText(firstName);
                                            inputFields[FIELD_MIDNAME].setText(middleName);
                                            inputFields[FIELD_SURNAME].setText(lastName);
                                            showEditDoneProgress(true, true);
                                            onIdentityDone(finishRunnable, errorRunnable);
                                        });
                                builder.setNegativeButton(LocaleController.getString("Edit", R.string.Edit),
                                        (dialogInterface, i) -> onFieldError(inputFields[num]));
                                showDialog(builder.create());
                            } else {
                                onFieldError(inputFields[a]);
                            }
                        }
                    }
                }
                if (error) {
                    return false;
                }
            }
            if (isHasNotAnyChanges()) {
                finishFragment();
                return false;
            }
            JSONObject json = null;
            JSONObject documentsJson = null;
            try {
                if (!documentOnly) {
                    HashMap<String, String> valuesToSave = new HashMap<>(currentValues);
                    if (currentType.native_names) {
                        if (nativeInfoCell.getVisibility() == View.VISIBLE) {
                            valuesToSave.put("first_name_native",
                                    inputExtraFields[FIELD_NATIVE_NAME].getText().toString());
                            valuesToSave.put("middle_name_native",
                                    inputExtraFields[FIELD_NATIVE_MIDNAME].getText().toString());
                            valuesToSave.put("last_name_native",
                                    inputExtraFields[FIELD_NATIVE_SURNAME].getText().toString());
                        } else {
                            valuesToSave.put("first_name_native",
                                    inputFields[FIELD_NATIVE_NAME].getText().toString());
                            valuesToSave.put("middle_name_native",
                                    inputFields[FIELD_NATIVE_MIDNAME].getText().toString());
                            valuesToSave.put("last_name_native",
                                    inputFields[FIELD_NATIVE_SURNAME].getText().toString());
                        }
                    }
                    valuesToSave.put("first_name", inputFields[FIELD_NAME].getText().toString());
                    valuesToSave.put("middle_name", inputFields[FIELD_MIDNAME].getText().toString());
                    valuesToSave.put("last_name", inputFields[FIELD_SURNAME].getText().toString());
                    valuesToSave.put("birth_date", inputFields[FIELD_BIRTHDAY].getText().toString());
                    valuesToSave.put("gender", currentGender);
                    valuesToSave.put("country_code", currentCitizeship);
                    valuesToSave.put("residence_country_code", currentResidence);

                    json = new JSONObject();
                    ArrayList<String> keys = new ArrayList<>(valuesToSave.keySet());
                    Collections.sort(keys, (key1, key2) -> {
                        int val1 = getFieldCost(key1);
                        int val2 = getFieldCost(key2);
                        if (val1 < val2) {
                            return -1;
                        } else if (val1 > val2) {
                            return 1;
                        }
                        return 0;
                    });
                    for (int a = 0, size = keys.size(); a < size; a++) {
                        String key = keys.get(a);
                        json.put(key, valuesToSave.get(key));
                    }
                }

                if (currentDocumentsType != null) {
                    HashMap<String, String> valuesToSave = new HashMap<>(currentDocumentValues);
                    valuesToSave.put("document_no", inputFields[FIELD_CARDNUMBER].getText().toString());
                    if (currentExpireDate[0] != 0) {
                        valuesToSave.put("expiry_date", String.format(Locale.US, "%02d.%02d.%d",
                                currentExpireDate[2], currentExpireDate[1], currentExpireDate[0]));
                    } else {
                        valuesToSave.put("expiry_date", "");
                    }

                    documentsJson = new JSONObject();
                    ArrayList<String> keys = new ArrayList<>(valuesToSave.keySet());
                    Collections.sort(keys, (key1, key2) -> {
                        int val1 = getFieldCost(key1);
                        int val2 = getFieldCost(key2);
                        if (val1 < val2) {
                            return -1;
                        } else if (val1 > val2) {
                            return 1;
                        }
                        return 0;
                    });
                    for (int a = 0, size = keys.size(); a < size; a++) {
                        String key = keys.get(a);
                        documentsJson.put(key, valuesToSave.get(key));
                    }
                }
            } catch (Exception ignore) {

            }
            if (fieldsErrors != null) {
                fieldsErrors.clear();
            }
            if (documentsErrors != null) {
                documentsErrors.clear();
            }
            delegate.saveValue(currentType, null, json != null ? json.toString() : null, currentDocumentsType,
                    documentsJson != null ? documentsJson.toString() : null, null, selfieDocument,
                    translationDocuments, frontDocument,
                    reverseLayout != null && reverseLayout.getVisibility() == View.VISIBLE ? reverseDocument
                            : null,
                    finishRunnable, errorRunnable);
            return true;
        }

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (checkDiscard()) {
                    return;
                }
                if (currentActivityType == TYPE_REQUEST || currentActivityType == TYPE_PASSWORD) {
                    callCallback(false);
                }
                finishFragment();
            } else if (id == info_item) {
                if (getParentActivity() == null) {
                    return;
                }
                final TextView message = new TextView(getParentActivity());
                String str2 = LocaleController.getString("PassportInfo2", R.string.PassportInfo2);
                SpannableStringBuilder spanned = new SpannableStringBuilder(str2);
                int index1 = str2.indexOf('*');
                int index2 = str2.lastIndexOf('*');
                if (index1 != -1 && index2 != -1) {
                    spanned.replace(index2, index2 + 1, "");
                    spanned.replace(index1, index1 + 1, "");
                    spanned.setSpan(new URLSpanNoUnderline(
                            LocaleController.getString("PassportInfoUrl", R.string.PassportInfoUrl)) {
                        @Override
                        public void onClick(View widget) {
                            dismissCurrentDialig();
                            super.onClick(widget);
                        }
                    }, index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                message.setText(spanned);
                message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                message.setLinkTextColor(Theme.getColor(Theme.key_dialogTextLink));
                message.setHighlightColor(Theme.getColor(Theme.key_dialogLinkSelection));
                message.setPadding(AndroidUtilities.dp(23), 0, AndroidUtilities.dp(23), 0);
                message.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
                message.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));

                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setView(message);
                builder.setTitle(LocaleController.getString("PassportInfoTitle", R.string.PassportInfoTitle));
                builder.setNegativeButton(LocaleController.getString("Close", R.string.Close), null);
                showDialog(builder.create());
            } else if (id == done_button) {
                if (currentActivityType == TYPE_PASSWORD) {
                    onPasswordDone(false);
                    return;
                }
                if (currentActivityType == TYPE_PHONE_VERIFICATION) {
                    views[currentViewNum].onNextPressed();
                } else {
                    final Runnable finishRunnable = () -> finishFragment();
                    final ErrorRunnable errorRunnable = new ErrorRunnable() {
                        @Override
                        public void onError(String error, String text) {
                            if ("PHONE_VERIFICATION_NEEDED".equals(error)) {
                                startPhoneVerification(true, text, finishRunnable, this, delegate);
                            } else {
                                showEditDoneProgress(true, false);
                            }
                        }
                    };

                    if (currentActivityType == TYPE_EMAIL) {
                        String value;
                        if (useCurrentValue) {
                            value = currentEmail;
                        } else {
                            if (checkFieldsForError()) {
                                return;
                            }
                            value = inputFields[FIELD_EMAIL].getText().toString();
                        }
                        delegate.saveValue(currentType, value, null, null, null, null, null, null, null, null,
                                finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_PHONE) {
                        String value;
                        if (useCurrentValue) {
                            value = UserConfig.getInstance(currentAccount).getCurrentUser().phone;
                        } else {
                            if (checkFieldsForError()) {
                                return;
                            }
                            value = inputFields[FIELD_PHONECODE].getText().toString()
                                    + inputFields[FIELD_PHONE].getText().toString();
                        }
                        delegate.saveValue(currentType, value, null, null, null, null, null, null, null, null,
                                finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_ADDRESS) {
                        if (!uploadingDocuments.isEmpty() || checkFieldsForError()) {
                            return;
                        }
                        if (isHasNotAnyChanges()) {
                            finishFragment();
                            return;
                        }
                        JSONObject json = null;
                        try {
                            if (!documentOnly) {
                                json = new JSONObject();
                                json.put("street_line1", inputFields[FIELD_STREET1].getText().toString());
                                json.put("street_line2", inputFields[FIELD_STREET2].getText().toString());
                                json.put("post_code", inputFields[FIELD_POSTCODE].getText().toString());
                                json.put("city", inputFields[FIELD_CITY].getText().toString());
                                json.put("state", inputFields[FIELD_STATE].getText().toString());
                                json.put("country_code", currentCitizeship);
                            }
                        } catch (Exception ignore) {

                        }
                        if (fieldsErrors != null) {
                            fieldsErrors.clear();
                        }
                        if (documentsErrors != null) {
                            documentsErrors.clear();
                        }
                        delegate.saveValue(currentType, null, json != null ? json.toString() : null,
                                currentDocumentsType, null, documents, selfieDocument, translationDocuments,
                                null, null, finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_IDENTITY) {
                        if (!onIdentityDone(finishRunnable, errorRunnable)) {
                            return;
                        }
                    } else if (currentActivityType == TYPE_EMAIL_VERIFICATION) {
                        final TLRPC.TL_account_verifyEmail req = new TLRPC.TL_account_verifyEmail();
                        req.email = currentValues.get("email");
                        req.code = inputFields[FIELD_EMAIL].getText().toString();
                        int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req,
                                (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                                    if (error == null) {
                                        delegate.saveValue(currentType, currentValues.get("email"), null, null,
                                                null, null, null, null, null, null, finishRunnable,
                                                errorRunnable);
                                    } else {
                                        AlertsCreator.processError(currentAccount, error, PassportActivity.this,
                                                req);
                                        errorRunnable.onError(null, null);
                                    }
                                }));
                        ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
                    }
                    showEditDoneProgress(true, true);
                }
            }
        }
    });

    if (currentActivityType == TYPE_PHONE_VERIFICATION) {
        fragmentView = scrollView = new ScrollView(context) {
            @Override
            protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
                return false;
            }

            @Override
            public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
                if (currentViewNum == 1 || currentViewNum == 2 || currentViewNum == 4) {
                    rectangle.bottom += AndroidUtilities.dp(40);
                }
                return super.requestChildRectangleOnScreen(child, rectangle, immediate);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                scrollHeight = MeasureSpec.getSize(heightMeasureSpec) - AndroidUtilities.dp(30);
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        };
        scrollView.setFillViewport(true);
        AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault));
    } else {
        fragmentView = new FrameLayout(context);
        FrameLayout frameLayout = (FrameLayout) fragmentView;
        fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));

        scrollView = new ScrollView(context) {
            @Override
            protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
                return false;
            }

            @Override
            public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
                rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY());
                rectangle.top += AndroidUtilities.dp(20);
                rectangle.bottom += AndroidUtilities.dp(50);
                return super.requestChildRectangleOnScreen(child, rectangle, immediate);
            }
        };
        scrollView.setFillViewport(true);
        AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault));
        frameLayout.addView(scrollView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
                        Gravity.LEFT | Gravity.TOP, 0, 0, 0, currentActivityType == TYPE_REQUEST ? 48 : 0));

        linearLayout2 = new LinearLayout(context);
        linearLayout2.setOrientation(LinearLayout.VERTICAL);
        scrollView.addView(linearLayout2, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
    }

    if (currentActivityType != TYPE_REQUEST && currentActivityType != TYPE_MANAGE) {
        ActionBarMenu menu = actionBar.createMenu();
        doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
        progressView = new ContextProgressView(context, 1);
        progressView.setAlpha(0.0f);
        progressView.setScaleX(0.1f);
        progressView.setScaleY(0.1f);
        progressView.setVisibility(View.INVISIBLE);
        doneItem.addView(progressView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

        if (currentActivityType == TYPE_IDENTITY || currentActivityType == TYPE_ADDRESS) {
            if (chatAttachAlert != null) {
                try {
                    if (chatAttachAlert.isShowing()) {
                        chatAttachAlert.dismiss();
                    }
                } catch (Exception ignore) {

                }
                chatAttachAlert.onDestroy();
                chatAttachAlert = null;
            }
        }
    }

    if (currentActivityType == TYPE_PASSWORD) {
        createPasswordInterface(context);
    } else if (currentActivityType == TYPE_REQUEST) {
        createRequestInterface(context);
    } else if (currentActivityType == TYPE_IDENTITY) {
        createIdentityInterface(context);
        fillInitialValues();
    } else if (currentActivityType == TYPE_ADDRESS) {
        createAddressInterface(context);
        fillInitialValues();
    } else if (currentActivityType == TYPE_PHONE) {
        createPhoneInterface(context);
    } else if (currentActivityType == TYPE_EMAIL) {
        createEmailInterface(context);
    } else if (currentActivityType == TYPE_EMAIL_VERIFICATION) {
        createEmailVerificationInterface(context);
    } else if (currentActivityType == TYPE_PHONE_VERIFICATION) {
        createPhoneVerificationInterface(context);
    } else if (currentActivityType == TYPE_MANAGE) {
        createManageInterface(context);
    }
    return fragmentView;
}

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

private void createRequestInterface(Context context) {
    TLRPC.User botUser = null;/*w  ww  .ja  v a 2  s. c  o m*/
    if (currentForm != null) {
        for (int a = 0; a < currentForm.users.size(); a++) {
            TLRPC.User user = currentForm.users.get(a);
            if (user.id == currentBotId) {
                botUser = user;
                break;
            }
        }
    }

    FrameLayout frameLayout = (FrameLayout) fragmentView;

    actionBar.setTitle(LocaleController.getString("TelegramPassport", R.string.TelegramPassport));

    actionBar.createMenu().addItem(info_item, R.drawable.profile_info);

    if (botUser != null) {
        FrameLayout avatarContainer = new FrameLayout(context);
        linearLayout2.addView(avatarContainer, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 100));

        BackupImageView avatarImageView = new BackupImageView(context);
        avatarImageView.setRoundRadius(AndroidUtilities.dp(32));
        avatarContainer.addView(avatarImageView, LayoutHelper.createFrame(64, 64, Gravity.CENTER, 0, 8, 0, 0));

        AvatarDrawable avatarDrawable = new AvatarDrawable(botUser);
        TLRPC.FileLocation photo = null;
        if (botUser.photo != null) {
            photo = botUser.photo.photo_small;
        }
        avatarImageView.setImage(photo, "50_50", avatarDrawable, botUser);

        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_top,
                Theme.key_windowBackgroundGrayShadow));
        bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportRequest",
                R.string.PassportRequest, UserObject.getFirstName(botUser))));
        bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
        ((FrameLayout.LayoutParams) bottomCell.getTextView()
                .getLayoutParams()).gravity = Gravity.CENTER_HORIZONTAL;
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    headerCell = new HeaderCell(context);
    headerCell.setText(
            LocaleController.getString("PassportRequestedInformation", R.string.PassportRequestedInformation));
    headerCell.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundWhite));
    linearLayout2.addView(headerCell,
            LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

    if (currentForm != null) {
        int size = currentForm.required_types.size();
        ArrayList<TLRPC.TL_secureRequiredType> personalDocuments = new ArrayList<>();
        ArrayList<TLRPC.TL_secureRequiredType> addressDocuments = new ArrayList<>();
        int personalCount = 0;
        int addressCount = 0;
        boolean hasPersonalInfo = false;
        boolean hasAddressInfo = false;
        for (int a = 0; a < size; a++) {
            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                if (isPersonalDocument(requiredType.type)) {
                    personalDocuments.add(requiredType);
                    personalCount++;
                } else if (isAddressDocument(requiredType.type)) {
                    addressDocuments.add(requiredType);
                    addressCount++;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
                    hasPersonalInfo = true;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) {
                    hasAddressInfo = true;
                }
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0);
                if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                TLRPC.TL_secureRequiredType requiredType = (TLRPC.TL_secureRequiredType) innerType;

                if (isPersonalDocument(requiredType.type)) {
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        personalDocuments.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    personalCount++;
                } else if (isAddressDocument(requiredType.type)) {
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        addressDocuments.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    addressCount++;
                }
            }
        }
        boolean separatePersonal = !hasPersonalInfo || personalCount > 1;
        boolean separateAddress = !hasAddressInfo || addressCount > 1;
        for (int a = 0; a < size; a++) {
            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            ArrayList<TLRPC.TL_secureRequiredType> documentTypes;
            TLRPC.TL_secureRequiredType requiredType;
            boolean documentOnly;
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                if (requiredType.type instanceof TLRPC.TL_secureValueTypePhone
                        || requiredType.type instanceof TLRPC.TL_secureValueTypeEmail) {
                    documentTypes = null;
                    documentOnly = false;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypePersonalDetails) {
                    if (separatePersonal) {
                        documentTypes = null;
                    } else {
                        documentTypes = personalDocuments;
                    }
                    documentOnly = false;
                } else if (requiredType.type instanceof TLRPC.TL_secureValueTypeAddress) {
                    if (separateAddress) {
                        documentTypes = null;
                    } else {
                        documentTypes = addressDocuments;
                    }
                    documentOnly = false;
                } else if (separatePersonal && isPersonalDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    documentTypes.add(requiredType);
                    requiredType = new TLRPC.TL_secureRequiredType();
                    requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails();
                    documentOnly = true;
                } else if (separateAddress && isAddressDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    documentTypes.add(requiredType);
                    requiredType = new TLRPC.TL_secureRequiredType();
                    requiredType.type = new TLRPC.TL_secureValueTypeAddress();
                    documentOnly = true;
                } else {
                    continue;
                }
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                TLRPC.SecureRequiredType innerType = requiredTypeOneOf.types.get(0);
                if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                requiredType = (TLRPC.TL_secureRequiredType) innerType;

                if (separatePersonal && isPersonalDocument(requiredType.type)
                        || separateAddress && isAddressDocument(requiredType.type)) {
                    documentTypes = new ArrayList<>();
                    for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                        innerType = requiredTypeOneOf.types.get(b);
                        if (!(innerType instanceof TLRPC.TL_secureRequiredType)) {
                            continue;
                        }
                        documentTypes.add((TLRPC.TL_secureRequiredType) innerType);
                    }
                    if (isPersonalDocument(requiredType.type)) {
                        requiredType = new TLRPC.TL_secureRequiredType();
                        requiredType.type = new TLRPC.TL_secureValueTypePersonalDetails();
                    } else {
                        requiredType = new TLRPC.TL_secureRequiredType();
                        requiredType.type = new TLRPC.TL_secureValueTypeAddress();
                    }

                    documentOnly = true;
                } else {
                    continue;
                }
            } else {
                continue;
            }
            addField(context, requiredType, documentTypes, documentOnly, a == size - 1);
        }
    }

    if (botUser != null) {
        bottomCell = new TextInfoPrivacyCell(context);
        bottomCell.setBackgroundDrawable(Theme.getThemedDrawable(context, R.drawable.greydivider_bottom,
                Theme.key_windowBackgroundGrayShadow));
        bottomCell.setLinkTextColorKey(Theme.key_windowBackgroundWhiteGrayText4);
        if (!TextUtils.isEmpty(currentForm.privacy_policy_url)) {
            String str2 = LocaleController.formatString("PassportPolicy", R.string.PassportPolicy,
                    UserObject.getFirstName(botUser), botUser.username);
            SpannableStringBuilder text = new SpannableStringBuilder(str2);
            int index1 = str2.indexOf('*');
            int index2 = str2.lastIndexOf('*');
            if (index1 != -1 && index2 != -1) {
                bottomCell.getTextView().setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
                text.replace(index2, index2 + 1, "");
                text.replace(index1, index1 + 1, "");
                text.setSpan(new LinkSpan(), index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            bottomCell.setText(text);
        } else {
            bottomCell.setText(AndroidUtilities.replaceTags(LocaleController.formatString("PassportNoPolicy",
                    R.string.PassportNoPolicy, UserObject.getFirstName(botUser), botUser.username)));
        }
        bottomCell.getTextView().setHighlightColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText4));
        bottomCell.getTextView().setGravity(Gravity.CENTER_HORIZONTAL);
        linearLayout2.addView(bottomCell,
                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
    }

    bottomLayout = new FrameLayout(context);
    bottomLayout.setBackgroundDrawable(
            Theme.createSelectorWithBackgroundDrawable(Theme.getColor(Theme.key_passport_authorizeBackground),
                    Theme.getColor(Theme.key_passport_authorizeBackgroundSelected)));
    frameLayout.addView(bottomLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 48, Gravity.BOTTOM));
    bottomLayout.setOnClickListener(view -> {

        class ValueToSend {
            TLRPC.TL_secureValue value;
            boolean selfie_required;
            boolean translation_required;

            public ValueToSend(TLRPC.TL_secureValue v, boolean s, boolean t) {
                value = v;
                selfie_required = s;
                translation_required = t;
            }
        }

        ArrayList<ValueToSend> valuesToSend = new ArrayList<>();
        for (int a = 0, size = currentForm.required_types.size(); a < size; a++) {

            TLRPC.TL_secureRequiredType requiredType;

            TLRPC.SecureRequiredType secureRequiredType = currentForm.required_types.get(a);
            if (secureRequiredType instanceof TLRPC.TL_secureRequiredType) {
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;
            } else if (secureRequiredType instanceof TLRPC.TL_secureRequiredTypeOneOf) {
                TLRPC.TL_secureRequiredTypeOneOf requiredTypeOneOf = (TLRPC.TL_secureRequiredTypeOneOf) secureRequiredType;
                if (requiredTypeOneOf.types.isEmpty()) {
                    continue;
                }
                secureRequiredType = requiredTypeOneOf.types.get(0);
                if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) {
                    continue;
                }
                requiredType = (TLRPC.TL_secureRequiredType) secureRequiredType;

                for (int b = 0, size2 = requiredTypeOneOf.types.size(); b < size2; b++) {
                    secureRequiredType = requiredTypeOneOf.types.get(b);
                    if (!(secureRequiredType instanceof TLRPC.TL_secureRequiredType)) {
                        continue;
                    }
                    TLRPC.TL_secureRequiredType innerType = (TLRPC.TL_secureRequiredType) secureRequiredType;
                    if (getValueByType(innerType, true) != null) {
                        requiredType = innerType;
                        break;
                    }
                }
            } else {
                continue;
            }

            TLRPC.TL_secureValue value = getValueByType(requiredType, true);
            if (value == null) {
                Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                if (v != null) {
                    v.vibrate(200);
                }
                AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0);
                return;
            }
            String key = getNameForType(requiredType.type);
            HashMap<String, String> errors = errorsMap.get(key);
            if (errors != null && !errors.isEmpty()) {
                Vibrator v = (Vibrator) getParentActivity().getSystemService(Context.VIBRATOR_SERVICE);
                if (v != null) {
                    v.vibrate(200);
                }
                AndroidUtilities.shakeView(getViewByType(requiredType), 2, 0);
                return;
            }
            valuesToSend.add(
                    new ValueToSend(value, requiredType.selfie_required, requiredType.translation_required));
        }
        showEditDoneProgress(false, true);
        TLRPC.TL_account_acceptAuthorization req = new TLRPC.TL_account_acceptAuthorization();
        req.bot_id = currentBotId;
        req.scope = currentScope;
        req.public_key = currentPublicKey;
        JSONObject jsonObject = new JSONObject();
        for (int a = 0, size = valuesToSend.size(); a < size; a++) {
            ValueToSend valueToSend = valuesToSend.get(a);
            TLRPC.TL_secureValue secureValue = valueToSend.value;

            JSONObject data = new JSONObject();

            if (secureValue.plain_data != null) {
                if (secureValue.plain_data instanceof TLRPC.TL_securePlainEmail) {
                    TLRPC.TL_securePlainEmail securePlainEmail = (TLRPC.TL_securePlainEmail) secureValue.plain_data;
                } else if (secureValue.plain_data instanceof TLRPC.TL_securePlainPhone) {
                    TLRPC.TL_securePlainPhone securePlainPhone = (TLRPC.TL_securePlainPhone) secureValue.plain_data;
                }
            } else {
                try {
                    JSONObject result = new JSONObject();
                    if (secureValue.data != null) {
                        byte[] decryptedSecret = decryptValueSecret(secureValue.data.secret,
                                secureValue.data.data_hash);

                        data.put("data_hash",
                                Base64.encodeToString(secureValue.data.data_hash, Base64.NO_WRAP));
                        data.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));

                        result.put("data", data);
                    }
                    if (!secureValue.files.isEmpty()) {
                        JSONArray files = new JSONArray();
                        for (int b = 0, size2 = secureValue.files.size(); b < size2; b++) {
                            TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.files.get(b);
                            byte[] decryptedSecret = decryptValueSecret(secureFile.secret,
                                    secureFile.file_hash);

                            JSONObject file = new JSONObject();
                            file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                            file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                            files.put(file);
                        }
                        result.put("files", files);
                    }
                    if (secureValue.front_side instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.front_side;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject front = new JSONObject();
                        front.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        front.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("front_side", front);
                    }
                    if (secureValue.reverse_side instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.reverse_side;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject reverse = new JSONObject();
                        reverse.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        reverse.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("reverse_side", reverse);
                    }
                    if (valueToSend.selfie_required && secureValue.selfie instanceof TLRPC.TL_secureFile) {
                        TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.selfie;
                        byte[] decryptedSecret = decryptValueSecret(secureFile.secret, secureFile.file_hash);

                        JSONObject selfie = new JSONObject();
                        selfie.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                        selfie.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                        result.put("selfie", selfie);
                    }
                    if (valueToSend.translation_required && !secureValue.translation.isEmpty()) {
                        JSONArray translation = new JSONArray();
                        for (int b = 0, size2 = secureValue.translation.size(); b < size2; b++) {
                            TLRPC.TL_secureFile secureFile = (TLRPC.TL_secureFile) secureValue.translation
                                    .get(b);
                            byte[] decryptedSecret = decryptValueSecret(secureFile.secret,
                                    secureFile.file_hash);

                            JSONObject file = new JSONObject();
                            file.put("file_hash", Base64.encodeToString(secureFile.file_hash, Base64.NO_WRAP));
                            file.put("secret", Base64.encodeToString(decryptedSecret, Base64.NO_WRAP));
                            translation.put(file);
                        }
                        result.put("translation", translation);
                    }
                    jsonObject.put(getNameForType(secureValue.type), result);
                } catch (Exception ignore) {

                }
            }

            TLRPC.TL_secureValueHash hash = new TLRPC.TL_secureValueHash();
            hash.type = secureValue.type;
            hash.hash = secureValue.hash;
            req.value_hashes.add(hash);
        }
        JSONObject result = new JSONObject();
        try {
            result.put("secure_data", jsonObject);
        } catch (Exception ignore) {

        }
        if (currentPayload != null) {
            try {
                result.put("payload", currentPayload);
            } catch (Exception ignore) {

            }
        }
        if (currentNonce != null) {
            try {
                result.put("nonce", currentNonce);
            } catch (Exception ignore) {

            }
        }
        String json = result.toString();

        EncryptionResult encryptionResult = encryptData(AndroidUtilities.getStringBytes(json));

        req.credentials = new TLRPC.TL_secureCredentialsEncrypted();
        req.credentials.hash = encryptionResult.fileHash;
        req.credentials.data = encryptionResult.encryptedData;
        try {
            String key = currentPublicKey.replaceAll("\\n", "").replace("-----BEGIN PUBLIC KEY-----", "")
                    .replace("-----END PUBLIC KEY-----", "");
            KeyFactory kf = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(Base64.decode(key, Base64.DEFAULT));
            RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(keySpecX509);

            Cipher c = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding", "BC");
            c.init(Cipher.ENCRYPT_MODE, pubKey);
            req.credentials.secret = c.doFinal(encryptionResult.decrypyedFileSecret);
        } catch (Exception e) {
            FileLog.e(e);
        }
        int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req,
                (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                    if (error == null) {
                        ignoreOnFailure = true;
                        callCallback(true);
                        finishFragment();
                    } else {
                        showEditDoneProgress(false, false);
                        if ("APP_VERSION_OUTDATED".equals(error.text)) {
                            AlertsCreator.showUpdateAppAlert(getParentActivity(),
                                    LocaleController.getString("UpdateAppAlert", R.string.UpdateAppAlert),
                                    true);
                        } else {
                            showAlertWithText(LocaleController.getString("AppName", R.string.AppName),
                                    error.text);
                        }
                    }
                }));
        ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
    });

    acceptTextView = new TextView(context);
    acceptTextView.setCompoundDrawablePadding(AndroidUtilities.dp(8));
    acceptTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.authorize, 0, 0, 0);
    acceptTextView.setTextColor(Theme.getColor(Theme.key_passport_authorizeText));
    acceptTextView.setText(LocaleController.getString("PassportAuthorize", R.string.PassportAuthorize));
    acceptTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
    acceptTextView.setGravity(Gravity.CENTER);
    acceptTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
    bottomLayout.addView(acceptTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.CENTER));

    progressViewButton = new ContextProgressView(context, 0);
    progressViewButton.setVisibility(View.INVISIBLE);
    bottomLayout.addView(progressViewButton,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

    View shadow = new View(context);
    shadow.setBackgroundResource(R.drawable.header_shadow_reverse);
    frameLayout.addView(shadow,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 3, Gravity.LEFT | Gravity.BOTTOM, 0, 0, 0, 48));
}

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

private void checkTopErrorCell(boolean init) {
    if (topErrorCell == null) {
        return;//from   w ww  .  j  a v  a 2s. c om
    }
    SpannableStringBuilder stringBuilder = null;
    if (fieldsErrors != null && (init || errorsValues.containsKey("error_all"))) {
        String errorText = fieldsErrors.get("error_all");
        if (errorText != null) {
            stringBuilder = new SpannableStringBuilder(errorText);
            if (init) {
                errorsValues.put("error_all", "");
            }
        }
    }
    if (documentsErrors != null && (init || errorsValues.containsKey("error_document_all"))) {
        String errorText = documentsErrors.get("error_all");
        if (errorText != null) {
            if (stringBuilder == null) {
                stringBuilder = new SpannableStringBuilder(errorText);
            } else {
                stringBuilder.append("\n\n").append(errorText);
            }
            if (init) {
                errorsValues.put("error_document_all", "");
            }
        }
    }
    if (stringBuilder != null) {
        stringBuilder.setSpan(new ForegroundColorSpan(Theme.getColor(Theme.key_windowBackgroundWhiteRedText3)),
                0, stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        topErrorCell.setText(stringBuilder);
        topErrorCell.setVisibility(View.VISIBLE);
    } else if (topErrorCell.getVisibility() != View.GONE) {
        topErrorCell.setVisibility(View.GONE);
    }
}

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

private void createIdentityInterface(final Context context) {
    languageMap = new HashMap<>();
    try {//www  .j a  v  a  2 s.  c o m
        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;
            }
            MrzCameraActivity fragment = new MrzCameraActivity();
            fragment.setDelegate(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((name, shortName) -> {
                        int field12 = (Integer) v.getTag();
                        final EditTextBoldCursor editText = inputFields[field12];
                        if (field12 == FIELD_CITIZENSHIP) {
                            currentCitizeship = shortName;
                        } else {
                            currentResidence = shortName;
                        }
                        editText.setText(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);
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void makeLinkClickable(SpannableStringBuilder strBuilder, final URLSpan span) {
    int start = strBuilder.getSpanStart(span);
    int end = strBuilder.getSpanEnd(span);
    int flags = strBuilder.getSpanFlags(span);
    ClickableSpan clickable = new ClickableSpan() {
        public void onClick(View view) {
            if (!mLoadingPlugin) {
                mLoadingPlugin = true;/*ww w. j  ava 2  s.co m*/
                String url = span.getURL();

                if (url.startsWith("http://play.google.com/store/apps/details?id=")) {
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW,
                                Uri.parse(url.replace("http://play.google.com/store/apps", "market:/"))));
                    } catch (android.content.ActivityNotFoundException anfe) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    }

                    mLoadingPlugin = false;
                } else if (url.startsWith("plugin://") || url.startsWith("plugins://")) {
                    final File path = IOUtils.getDownloadDirectory(getApplicationContext());

                    if (!path.isDirectory()) {
                        path.mkdirs();
                    }

                    if (url.startsWith("plugin://")) {
                        url = url.replace("plugin://", "http://");
                    } else if (url.startsWith("plugins://")) {
                        url = url.replace("plugins://", "https://");
                    }

                    String name = url.substring(url.lastIndexOf("/") + 1);

                    mCurrentDownloadPlugin = new File(path, name);

                    if (mCurrentDownloadPlugin.isFile()) {
                        mCurrentDownloadPlugin.delete();
                    }

                    final String downloadUrl = url;

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            AsyncTask<String, Void, Boolean> async = new AsyncTask<String, Void, Boolean>() {
                                private ProgressDialog mProgress;
                                private File mPluginFile;

                                protected void onPreExecute() {
                                    mProgress = new ProgressDialog(TvBrowser.this);
                                    mProgress.setMessage(getString(R.string.plugin_info_donwload).replace("{0}",
                                            mCurrentDownloadPlugin.getName()));
                                    mProgress.show();
                                };

                                @Override
                                protected Boolean doInBackground(String... params) {
                                    mPluginFile = new File(params[0]);
                                    return IOUtils.saveUrl(params[0], params[1], 15000);
                                }

                                protected void onPostExecute(Boolean result) {
                                    mProgress.dismiss();

                                    if (result) {
                                        Intent intent = new Intent(Intent.ACTION_VIEW);
                                        intent.setDataAndType(Uri.fromFile(mPluginFile),
                                                "application/vnd.android.package-archive");
                                        TvBrowser.this.startActivityForResult(intent, INSTALL_PLUGIN);
                                    }

                                    mLoadingPlugin = false;
                                };
                            };

                            async.execute(mCurrentDownloadPlugin.toString(), downloadUrl);
                        }
                    });
                } else {
                    mLoadingPlugin = false;
                }
            }
        }
    };
    strBuilder.setSpan(clickable, start, end, flags);
    strBuilder.removeSpan(span);
}

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

private void applyDraftMaybe(boolean canClear) {
    if (chatActivityEnterView == null) {
        return;/*from  w  w w . j  av  a2s .co  m*/
    }
    TLRPC.DraftMessage draftMessage = DraftQuery.getDraft(dialog_id);
    TLRPC.Message draftReplyMessage = draftMessage != null && draftMessage.reply_to_msg_id != 0
            ? DraftQuery.getDraftMessage(dialog_id)
            : null;
    if (chatActivityEnterView.getFieldText() == null) {
        if (draftMessage != null) {
            chatActivityEnterView.setWebPage(null, !draftMessage.no_webpage);
            CharSequence message;
            if (!draftMessage.entities.isEmpty()) {
                SpannableStringBuilder stringBuilder = SpannableStringBuilder.valueOf(draftMessage.message);
                MessagesQuery.sortEntities(draftMessage.entities);
                int addToOffset = 0;
                for (int a = 0; a < draftMessage.entities.size(); a++) {
                    TLRPC.MessageEntity entity = draftMessage.entities.get(a);
                    if (entity instanceof TLRPC.TL_inputMessageEntityMentionName
                            || entity instanceof TLRPC.TL_messageEntityMentionName) {
                        int user_id;
                        if (entity instanceof TLRPC.TL_inputMessageEntityMentionName) {
                            user_id = ((TLRPC.TL_inputMessageEntityMentionName) entity).user_id.user_id;
                        } else {
                            user_id = ((TLRPC.TL_messageEntityMentionName) entity).user_id;
                        }
                        if (entity.offset + addToOffset + entity.length < stringBuilder.length()
                                && stringBuilder.charAt(entity.offset + addToOffset + entity.length) == ' ') {
                            entity.length++;
                        }
                        stringBuilder.setSpan(new URLSpanUserMention("" + user_id), entity.offset + addToOffset,
                                entity.offset + addToOffset + entity.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    } else if (entity instanceof TLRPC.TL_messageEntityCode) {
                        stringBuilder.insert(entity.offset + entity.length + addToOffset, "`");
                        stringBuilder.insert(entity.offset + addToOffset, "`");
                        addToOffset += 2;
                    } else if (entity instanceof TLRPC.TL_messageEntityPre) {
                        stringBuilder.insert(entity.offset + entity.length + addToOffset, "```");
                        stringBuilder.insert(entity.offset + addToOffset, "```");
                        addToOffset += 6;
                    }
                }
                message = stringBuilder;
            } else {
                message = draftMessage.message;
            }
            chatActivityEnterView.setFieldText(message);
            if (getArguments().getBoolean("hasUrl", false)) {
                chatActivityEnterView.setSelection(draftMessage.message.indexOf('\n') + 1);
                AndroidUtilities.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        if (chatActivityEnterView != null) {
                            chatActivityEnterView.setFieldFocused(true);
                            chatActivityEnterView.openKeyboard();
                        }
                    }
                }, 700);
            }
        }
    } else if (canClear && draftMessage == null) {
        chatActivityEnterView.setFieldText("");
        showReplyPanel(false, null, null, null, false, true);
    }
    if (replyingMessageObject == null && draftReplyMessage != null) {
        replyingMessageObject = new MessageObject(draftReplyMessage,
                MessagesController.getInstance().getUsers(), false);
        showReplyPanel(true, replyingMessageObject, null, null, false, false);
    }
}