Example usage for android.text Editable length

List of usage examples for android.text Editable length

Introduction

In this page you can find the example usage for android.text Editable length.

Prototype

int length();

Source Link

Document

Returns the length of this character sequence.

Usage

From source file:com.app.blockydemo.ui.dialogs.NewVariableDialog.java

private void handleOnShow(final Dialog dialogNewVariable) {
    final Button positiveButton = ((AlertDialog) dialogNewVariable).getButton(AlertDialog.BUTTON_POSITIVE);
    positiveButton.setEnabled(false);//from ww  w . j  a  v a  2 s . c o m

    EditText dialogEditText = (EditText) dialogNewVariable
            .findViewById(R.id.dialog_formula_editor_variable_name_edit_text);

    InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.showSoftInput(dialogEditText, InputMethodManager.SHOW_IMPLICIT);

    dialogEditText.addTextChangedListener(new TextWatcher() {

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

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {

            String variableName = editable.toString();
            if (ProjectManager.getInstance().getCurrentProject().getUserVariables()
                    .getUserVariable(variableName, ProjectManager.getInstance().getCurrentSprite()) != null) {

                Toast.makeText(getActivity(), R.string.formula_editor_existing_variable, Toast.LENGTH_SHORT)
                        .show();

                positiveButton.setEnabled(false);
            } else {
                positiveButton.setEnabled(true);
            }

            if (editable.length() == 0) {
                positiveButton.setEnabled(false);
            }
        }
    });
}

From source file:com.taobao.weex.dom.WXTextDomObject.java

/**
 * Truncate the source span to the specified lines.
 * Caller of this method must ensure that the lines of text is <strong>greater than desired lines and need truncate</strong>.
 * Otherwise, unexpected behavior may happen.
 * @param source The source span.//from   w  ww.  j a  va  2s  . c  o  m
 * @param paint the textPaint
 * @param desired specified lines.
 * @param truncateAt truncate method, null value means clipping overflow text directly, non-null value means using ellipsis strategy to clip
 * @return The spans after clipped.
 */
private @NonNull Spanned truncate(@Nullable Editable source, @NonNull TextPaint paint, int desired,
        @Nullable TextUtils.TruncateAt truncateAt) {
    Spanned ret = new SpannedString("");
    if (!TextUtils.isEmpty(source) && source.length() > 0) {
        if (truncateAt != null) {
            source.append(ELLIPSIS);
            Object[] spans = source.getSpans(0, source.length(), Object.class);
            for (Object span : spans) {
                int start = source.getSpanStart(span);
                int end = source.getSpanEnd(span);
                if (start == 0 && end == source.length() - 1) {
                    source.removeSpan(span);
                    source.setSpan(span, 0, source.length(), source.getSpanFlags(span));
                }
            }
        }

        StaticLayout layout;
        int startOffset;

        while (source.length() > 1) {
            startOffset = source.length() - 1;
            if (truncateAt != null) {
                startOffset -= 1;
            }
            source.delete(startOffset, startOffset + 1);
            layout = new StaticLayout(source, paint, desired, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
            if (layout.getLineCount() <= 1) {
                ret = source;
                break;
            }
        }
    }
    return ret;
}

From source file:eu.operando.operandoapp.filters.response.ResponseFiltersActivity.java

@OnClick(R.id.add_filter)
public void addFilter() {
    final EditText input = new EditText(this);
    input.setSingleLine(true);/*from   w  w w  . j a  va  2s .com*/
    if (viewSelected == 0) { //User Filter
        input.setHint("Filtered String");
        AlertDialog.Builder builder = new AlertDialog.Builder(this).setTitle("New ResponseFilter")
                .setView(input).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        ResponseFilter responseFilter = new ResponseFilter();
                        responseFilter.setContent(input.getText().toString());
                        responseFilter.setSource(null);
                        db.createResponseFilter(responseFilter);
                        updateFiltersList();
                        userResponseFiltersAdapter.notifyItemInserted(userFilters.size() - 1);
                        recyclerView.scrollToPosition(userFilters.size() - 1);
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                    }
                });

        final AlertDialog dialog = builder.create();

        input.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 1) {
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
                } else
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

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

        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
            }
        });

        dialog.show();

    } else { //Imported filter list
        input.setHint("Enter URL");
        new AlertDialog.Builder(this).setTitle("Import filters from remote file").setView(input)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        final String importUrl = input.getText().toString();
                        importExternalFilters(importUrl);

                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // Canceled.
                    }
                }).show();
    }
}

From source file:com.dabay6.android.apps.carlog.ui.vehicle.fragments.VehicleEditFragment.java

/**
 *
 *///from   www . j a  v  a2 s  . co m
@SuppressWarnings("deprecation")
@Override
protected void setupForm() {
    final int errorResId = R.string.field_required;
    final LoaderManager manager = getLoaderManager();
    final String[] fromModel = new String[] { Model.Columns.MODEL_NAME.getName() };
    final Context context = getActivity();

    if (AndroidUtils.isAtLeastHoneycomb()) {
        makeAdapter = new MakeCursorAdapter(context, null, 0);
        modelAdapter = new ModelCursorAdapter(context, null, 0);
    } else {
        makeAdapter = new MakeCursorAdapter(context, null);
        modelAdapter = new ModelCursorAdapter(context, null);
    }

    licensePlate = finder.find(id.license_plate);
    make = finder.find(R.id.make);
    model = finder.find(R.id.model);
    name = finder.find(R.id.name);
    vin = finder.find(R.id.vin);
    year = finder.find(R.id.year);

    validator.addValidator("make", new RequiredValidator(make, errorResId));
    validator.addValidator("model", new RequiredValidator(model, errorResId));

    make.setAdapter(makeAdapter);
    make.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, final int position,
                final long id) {
            modelAdapter.setMakeId(id);
        }
    });

    finder.addTextWatcher(new TextWatcher() {
        @Override
        public void afterTextChanged(final Editable s) {
        }

        @Override
        public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
        }

        @Override
        public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
            model.setEnabled(s.length() > 0);
        }
    }, make);

    finder.onEditorAction(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(final TextView view, final int actionId, final KeyEvent event) {
            onPositiveButtonClick();

            return true;
        }
    }, vin);

    model.setAdapter(modelAdapter);
    model.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, final View view, final int position,
                final long id) {
            modelId = id;
        }
    });

    manager.initLoader(MAKE_LOADER_ID, null, this);
    manager.initLoader(MODEL_LOADER_ID, null, this);
}

From source file:tv.acfun.a63.CommentsActivity.java

boolean validate() {
    mUser = AcApp.getUser();//from w  w w. j av a2s  .c  o  m
    if (mUser == null) {
        Toast.makeText(this, getString(R.string.sign_in_first), Toast.LENGTH_SHORT).show();
        startActivity(SigninActivity.createIntent(this));
        return false;
    }
    Editable text = mCommentText.getText();
    int len = text.length() - getQuoteSpanLength(text);
    if (len == 0) {
        Toast.makeText(this, getString(R.string.no_comment), Toast.LENGTH_SHORT).show();
        return false;
    }
    if (len <= 5) {
        Toast.makeText(this, getString(R.string.comment_not_enough), Toast.LENGTH_SHORT).show();
        return false;
    }
    return true;
}

From source file:org.mozilla.focus.widget.InlineAutocompleteEditText.java

/**
 * Add autocomplete text based on the result URI.
 *
 * @param result Result URI to be turned into autocomplete text
 *///from w  w w.  ja  v  a  2s  . c o m
public final void onAutocomplete(final String result) {
    // If mDiscardAutoCompleteResult is true, we temporarily disabled
    // autocomplete (due to backspacing, etc.) and we should bail early.
    if (mDiscardAutoCompleteResult) {
        return;
    }

    if (!isEnabled() || result == null) {
        mAutoCompleteResult = "";
        return;
    }

    final Editable text = getText();
    final int textLength = text.length();
    final int resultLength = result.length();
    final int autoCompleteStart = text.getSpanStart(AUTOCOMPLETE_SPAN);
    mAutoCompleteResult = result;

    if (autoCompleteStart > -1) {
        // Autocomplete text already exists; we should replace existing autocomplete text.

        // If the result and the current text don't have the same prefixes,
        // the result is stale and we should wait for the another result to come in.
        if (!TextUtils.regionMatches(result, 0, text, 0, autoCompleteStart)) {
            return;
        }

        beginSettingAutocomplete();

        // Replace the existing autocomplete text with new one.
        // replace() preserves the autocomplete spans that we set before.
        text.replace(autoCompleteStart, textLength, result, autoCompleteStart, resultLength);

        // Reshow the cursor if there is no longer any autocomplete text.
        if (autoCompleteStart == resultLength) {
            setCursorVisible(true);
        }

        endSettingAutocomplete();

    } else {
        // No autocomplete text yet; we should add autocomplete text

        // If the result prefix doesn't match the current text,
        // the result is stale and we should wait for the another result to come in.
        if (resultLength <= textLength || !TextUtils.regionMatches(result, 0, text, 0, textLength)) {
            return;
        }

        final Object[] spans = text.getSpans(textLength, textLength, Object.class);
        final int[] spanStarts = new int[spans.length];
        final int[] spanEnds = new int[spans.length];
        final int[] spanFlags = new int[spans.length];

        // Save selection/composing span bounds so we can restore them later.
        for (int i = 0; i < spans.length; i++) {
            final Object span = spans[i];
            final int spanFlag = text.getSpanFlags(span);

            // We don't care about spans that are not selection or composing spans.
            // For those spans, spanFlag[i] will be 0 and we don't restore them.
            if ((spanFlag & Spanned.SPAN_COMPOSING) == 0 && (span != Selection.SELECTION_START)
                    && (span != Selection.SELECTION_END)) {
                continue;
            }

            spanStarts[i] = text.getSpanStart(span);
            spanEnds[i] = text.getSpanEnd(span);
            spanFlags[i] = spanFlag;
        }

        beginSettingAutocomplete();

        // First add trailing text.
        text.append(result, textLength, resultLength);

        // Restore selection/composing spans.
        for (int i = 0; i < spans.length; i++) {
            final int spanFlag = spanFlags[i];
            if (spanFlag == 0) {
                // Skip if the span was ignored before.
                continue;
            }
            text.setSpan(spans[i], spanStarts[i], spanEnds[i], spanFlag);
        }

        // Mark added text as autocomplete text.
        for (final Object span : mAutoCompleteSpans) {
            text.setSpan(span, textLength, resultLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        // Hide the cursor.
        setCursorVisible(false);

        // Make sure the autocomplete text is visible. If the autocomplete text is too
        // long, it would appear the cursor will be scrolled out of view. However, this
        // is not the case in practice, because EditText still makes sure the cursor is
        // still in view.
        bringPointIntoView(resultLength);

        endSettingAutocomplete();
    }

    announceForAccessibility(text.toString());
}

From source file:com.app.blockydemo.ui.dialogs.ScriptNameDialog.java

private void handleOnShow(final Dialog dialogEditName) {
    final Button positiveButton = ((AlertDialog) dialogEditName).getButton(AlertDialog.BUTTON_POSITIVE);
    positiveButton.setEnabled(false);// w w  w.  j  av a2s.  c  o  m

    EditText dialogEditText = (EditText) dialogEditName.findViewById(R.id.dialog_editor_script_name_edit_text);

    InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.showSoftInput(dialogEditText, InputMethodManager.SHOW_IMPLICIT);

    dialogEditText.addTextChangedListener(new TextWatcher() {

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

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {

            String variableName = editable.toString();
            positiveButton.setEnabled(true);
            for (Script local_script : ProjectManager.getInstance().getCurrentSprite().getScriptList()) {
                if (local_script.getName().equals(variableName)
                        && !local_script.getName().equals(script.getName())) {
                    Toast.makeText(getActivity(), R.string.formula_editor_existing_variable, Toast.LENGTH_SHORT)
                            .show();
                    positiveButton.setEnabled(false);
                }
            }

            if (editable.length() == 0) {
                positiveButton.setEnabled(false);
            }
            if (editable.toString().equals(script.getName())) {
                positiveButton.setEnabled(false);
            }
        }
    });
    dialogEditText.setText(script.getName());

}

From source file:be.brunoparmentier.wifikeyshare.ui.activities.WifiNetworkActivity.java

void showWifiPasswordDialog() {
    final LayoutInflater inflater = getLayoutInflater();
    final View wifiPasswordDialogLayout = inflater.inflate(R.layout.dialog_wifi_password, null);

    final TextInputLayout wifiPasswordWrapper = (TextInputLayout) wifiPasswordDialogLayout
            .findViewById(R.id.wifi_key_wrapper);
    final EditText passwordEditText = (EditText) wifiPasswordDialogLayout.findViewById(R.id.wifi_key);
    //setPasswordRestrictions(passwordEditText);
    final CheckBox showPasswordCheckBox = (CheckBox) wifiPasswordDialogLayout
            .findViewById(R.id.show_password_checkbox);
    showPasswordCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override/*  w w w .j av  a2  s. com*/
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            int selectionIndex = passwordEditText.getSelectionStart();
            if (isChecked) {
                passwordEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                passwordEditText
                        .setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
            }
            passwordEditText.setSelection(selectionIndex);
        }
    });

    final AlertDialog wifiPasswordDialog = new AlertDialog.Builder(this)
            .setTitle(getString(R.string.wifi_dialog_password_title))
            .setMessage(String.format(getString(R.string.wifi_dialog_password_msg), wifiNetwork.getSsid()))
            .setView(wifiPasswordDialogLayout)
            .setPositiveButton(getString(R.string.action_ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // this method gets overriden after we show the dialog
                }
            }).setNegativeButton(getString(R.string.action_cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    finish();
                }
            }).create();

    passwordEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

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

        }

        @Override
        public void afterTextChanged(Editable editable) {
            wifiPasswordDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(editable.length() >= 5);
            if (wifiPasswordWrapper.getError() != null) {
                try {
                    if (WifiNetwork.isValidKeyLength(wifiNetwork.getAuthType(), editable.toString())) {
                        wifiPasswordWrapper.setError(null);
                    }
                } catch (final WifiException e) {
                    switch (e.getErrorCode()) {
                    case WifiException.WEP_KEY_LENGTH_ERROR:
                        wifiPasswordWrapper.setError(getString(R.string.error_wep_password_length));
                        break;
                    case WifiException.WPA_KEY_LENGTH_ERROR:
                        wifiPasswordWrapper.setError(getString(R.string.error_wpa_password_length));
                        break;
                    default:
                        wifiPasswordWrapper.setError(e.getMessage());
                        break;
                    }
                }
            }
        }
    });

    wifiPasswordDialog.show();

    wifiPasswordDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false); // disabled by default
    wifiPasswordDialog.getButton(DialogInterface.BUTTON_POSITIVE)
            .setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    try {
                        if (WifiNetwork.isValidKeyLength(wifiNetwork.getAuthType(),
                                passwordEditText.getText().toString())) {

                            wifiPasswordWrapper.setError(null);
                            wifiNetwork.setKey(passwordEditText.getText().toString());

                            // Update QR code image
                            FragmentManager fm = getSupportFragmentManager();
                            QrCodeFragment qrCodeFragment = (QrCodeFragment) fm.getFragments().get(0);
                            qrCodeFragment.updateQrCode(wifiNetwork);

                            WifiKeysDataSource.getInstance().insertWifiKey(wifiNetwork);

                            Intent passwordResultIntent = new Intent();
                            passwordResultIntent.putExtra(KEY_NETWORK_ID, wifiNetworkId);
                            setResult(RESULT_OK, passwordResultIntent);

                            wifiPasswordDialog.dismiss();
                        }
                    } catch (WifiException e) {
                        switch (e.getErrorCode()) {
                        case WifiException.WEP_KEY_LENGTH_ERROR:
                            wifiPasswordWrapper.setError(getString(R.string.error_wep_password_length));
                            break;
                        case WifiException.WPA_KEY_LENGTH_ERROR:
                            wifiPasswordWrapper.setError(getString(R.string.error_wpa_password_length));
                            break;
                        default:
                            wifiPasswordWrapper.setError(null);
                            break;
                        }
                    }
                }
            });
}

From source file:com.cmput301w15t15.travelclaimsapp.activitys.EditClaimActivity.java

@Override
public void afterTextChanged(Editable s) {

    switch (getCurrentFocus().getId()) {
    case R.id.Edit_Claim_Name2:
        String newName = s.toString();
        //if length of name in edittext is 0 or if claim name is already in claimlist
        //then do not save changes. Otherwise update the claim name
        if (s.length() == 0) {
            Toast.makeText(this, "Claim name cannot be null", Toast.LENGTH_SHORT).show();
        } else if (claimList.getClaim(newName) != null) {
            Toast.makeText(this, "Claim name cannot be duplicate of another claim", Toast.LENGTH_SHORT).show();
        } else {/*from w  ww.ja va 2  s  .c o m*/
            theClaim.setName(claimNameInput.getText().toString());
        }
    case R.id.Claim_Start_Date:
        try {
            theClaim.setStartDate(sdf.parse(claimStartDate.getText().toString()));
        } catch (ParseException e) {
            //do nothing 
        }
    case R.id.Claim_Finish_Date:
        try {
            theClaim.setEndDate(sdf.parse(claimEndDate.getText().toString()));
        } catch (ParseException e) {
            //do nothing
        }
    }

}

From source file:com.ruesga.rview.widget.TagEditTextView.java

private void createChip(Editable s, boolean nextIsTag) {
    int start = mTagList.size();
    int end = s.length() + (nextIsTag ? -1 : 0);
    String tagText = s.subSequence(start, end).toString().trim();
    tagText = NON_UNICODE_CHAR_PATTERN.matcher(tagText).replaceAll("");
    if (tagText.isEmpty() || tagText.length() <= 1) {
        // User is still writing
        return;//from   w w  w .  ja v  a2s. co  m
    }
    String charText = tagText.substring(0, 1);
    if (!VALID_TAGS.contains(charText) || (charText.charAt(0) == VALID_TAGS.charAt(1) && !mSupportsUserTags)) {
        char tag = mDefaultTagMode == TAG_MODE.HASH ? VALID_TAGS.charAt(0) : VALID_TAGS.charAt(1);
        tagText = tag + tagText;
    }

    // Replace the new tag
    s.replace(start, end, CHIP_REPLACEMENT_CHAR);

    // Create the tag and its spannable
    final Tag tag = new Tag();
    tag.mTag = NON_UNICODE_CHAR_PATTERN.matcher(tagText).replaceAll("");
    Bitmap b = createTagChip(tag);
    ImageSpan span = new ImageSpan(getContext(), b);
    s.setSpan(span, start, start + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    tag.w = b.getWidth();
    tag.h = b.getHeight();
    mTagList.add(tag);

    notifyTagCreated(tag);
}