Example usage for android.widget TextView setHighlightColor

List of usage examples for android.widget TextView setHighlightColor

Introduction

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

Prototype

@android.view.RemotableViewMethod
public void setHighlightColor(@ColorInt int color) 

Source Link

Document

Sets the color used to display the selection highlight.

Usage

From source file:xyz.klinker.android.article.Utils.java

/**
 * Changes the text selection handle colors.
 *//*w ww .j ava 2s. c  o  m*/
static void changeTextSelectionHandleColors(TextView textView, int color) {
    textView.setHighlightColor(Color.argb(40, Color.red(color), Color.green(color), Color.blue(color)));

    try {
        Field editorField = TextView.class.getDeclaredField("mEditor");
        if (!editorField.isAccessible()) {
            editorField.setAccessible(true);
        }

        Object editor = editorField.get(textView);
        Class<?> editorClass = editor.getClass();

        String[] handleNames = { "mSelectHandleLeft", "mSelectHandleRight", "mSelectHandleCenter" };
        String[] resNames = { "mTextSelectHandleLeftRes", "mTextSelectHandleRightRes", "mTextSelectHandleRes" };

        for (int i = 0; i < handleNames.length; i++) {
            Field handleField = editorClass.getDeclaredField(handleNames[i]);
            if (!handleField.isAccessible()) {
                handleField.setAccessible(true);
            }

            Drawable handleDrawable = (Drawable) handleField.get(editor);

            if (handleDrawable == null) {
                Field resField = TextView.class.getDeclaredField(resNames[i]);
                if (!resField.isAccessible()) {
                    resField.setAccessible(true);
                }
                int resId = resField.getInt(textView);
                handleDrawable = ContextCompat.getDrawable(textView.getContext(), resId);
            }

            if (handleDrawable != null) {
                Drawable drawable = handleDrawable.mutate();
                drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
                handleField.set(editor, drawable);
            }
        }
    } catch (Exception ignored) {
    }
}

From source file:arun.com.chromer.browsing.article.util.ArticleUtil.java

/**
 * Changes the text selection handle colors.
 *///  w  w  w. j a  v a2 s. c  om
public static void changeTextSelectionHandleColors(TextView textView, int color) {
    textView.setHighlightColor(Color.argb(40, Color.red(color), Color.green(color), Color.blue(color)));

    try {
        Field editorField = TextView.class.getDeclaredField("mEditor");
        if (!editorField.isAccessible()) {
            editorField.setAccessible(true);
        }

        Object editor = editorField.get(textView);
        Class<?> editorClass = editor.getClass();

        String[] handleNames = { "mSelectHandleLeft", "mSelectHandleRight", "mSelectHandleCenter" };
        String[] resNames = { "mTextSelectHandleLeftRes", "mTextSelectHandleRightRes", "mTextSelectHandleRes" };

        for (int i = 0; i < handleNames.length; i++) {
            Field handleField = editorClass.getDeclaredField(handleNames[i]);
            if (!handleField.isAccessible()) {
                handleField.setAccessible(true);
            }

            Drawable handleDrawable = (Drawable) handleField.get(editor);

            if (handleDrawable == null) {
                Field resField = TextView.class.getDeclaredField(resNames[i]);
                if (!resField.isAccessible()) {
                    resField.setAccessible(true);
                }
                int resId = resField.getInt(textView);
                handleDrawable = ContextCompat.getDrawable(textView.getContext(), resId);
            }

            if (handleDrawable != null) {
                Drawable drawable = handleDrawable.mutate();
                drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
                handleField.set(editor, drawable);
            }
        }
    } catch (Exception ignored) {
    }
}

From source file:com.github.dfa.diaspora_android.ui.theme.ThemeHelper.java

public static void updateTextViewLinkColor(TextView textView) {
    if (textView != null) {
        textView.setHighlightColor(getInstance().appSettings.getAccentColor());
        textView.setLinkTextColor(getInstance().appSettings.getAccentColor());
    }/*w ww . j  ava 2 s. c  o m*/
}

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;
            }//  w w  w. ja v  a  2s .  c  om
            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;
}