Example usage for android.text InputFilter InputFilter

List of usage examples for android.text InputFilter InputFilter

Introduction

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

Prototype

InputFilter

Source Link

Usage

From source file:com.j_o.android.imdb_client.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mediaList = new ArrayList<Media>();
    mediaGrid = (GridView) findViewById(R.id.media_grid_view);
    editTxMediaSearch = (EditText) findViewById(R.id.edit_search_media);

    // Input filter that not allow special characters.
    InputFilter filter = new InputFilter() {
        @Override/*  w  ww. ja  v  a 2s . c  om*/
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {

            if (source instanceof SpannableStringBuilder) {
                SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder) source;
                for (int i = end - 1; i >= start; i--) {
                    char currentChar = source.charAt(i);
                    if (!Character.isLetterOrDigit(currentChar) && !Character.isSpaceChar(currentChar)) {
                        sourceAsSpannableBuilder.delete(i, i + 1);
                    }
                }
                return source;
            } else {
                StringBuilder filteredStringBuilder = new StringBuilder();
                for (int i = 0; i < end; i++) {
                    char currentChar = source.charAt(i);
                    if (Character.isLetterOrDigit(currentChar) || Character.isSpaceChar(currentChar)) {
                        filteredStringBuilder.append(currentChar);
                    }
                }
                return filteredStringBuilder.toString();
            }
        }
    };
    editTxMediaSearch.setFilters(new InputFilter[] { filter });

    editTxMediaSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                new AskForMediaAsyncTaks().execute(editTxMediaSearch.getText().toString());
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(editTxMediaSearch.getWindowToken(), 0);
                return true;
            }
            return false;
        }

    });

}

From source file:com.jins_meme.bridge.OSCConfigFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    handler = new Handler();

    layout = (LinearLayout) view.findViewById(R.id.osc_layout);
    layout.setOnTouchListener(new OnTouchListener() {
        @Override// ww w.ja  v a 2 s .  c  o  m
        public boolean onTouch(View view, MotionEvent motionEvent) {
            Log.d("DEBUG", "view touch.");

            layout.requestFocus();

            return false;
        }
    });

    InputFilter[] filters = new InputFilter[1];
    filters[0] = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            if (end > start) {
                String destTxt = dest.toString();
                String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end)
                        + destTxt.substring(dend);
                if (!resultingTxt
                        .matches("^\\d{1,3}(\\." + "(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
                    return "";
                } else {
                    String[] splits = resultingTxt.split("\\.");
                    for (String split : splits) {
                        if (Integer.valueOf(split) > 255) {
                            return "";
                        }
                    }
                }
            }
            return null;
        }
    };

    etRemoteIP = (EditText) view.findViewById(R.id.remote_ip);
    String savedRemoteIP = ((MainActivity) getActivity()).getSavedValue("REMOTE_IP", "255.255.255.255");
    if (savedRemoteIP.equals("255.255.255.255")) {
        etRemoteIP.setText(MemeOSC.getRemoteIPv4Address());
    } else {
        etRemoteIP.setText(savedRemoteIP);
    }
    etRemoteIP.setFilters(filters);
    etRemoteIP.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });
    etRemoteIP.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) {
            Log.d("DEBUG", "after text changed " + editable.toString());

            ((MainActivity) getActivity()).autoSaveValue("REMOTE_IP", editable.toString());

            testOSC.setRemoteIP(etRemoteIP.getText().toString());
            testOSC.initSocket();
        }
    });

    etRemotePort = (EditText) view.findViewById(R.id.remote_port);
    etRemotePort.setText(String.valueOf(((MainActivity) getActivity()).getSavedValue("REMOTE_PORT", 10316)));
    etRemotePort.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });
    etRemotePort.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) {
            Log.d("DEBUG", "after text changed " + editable.toString());

            if (editable.toString().length() > 0) {
                ((MainActivity) getActivity()).autoSaveValue("REMOTE_PORT",
                        Integer.valueOf(editable.toString()));

                testOSC.setRemotePort(Integer.parseInt(editable.toString()));
                testOSC.initSocket();
            }
        }
    });

    etHostIP = (EditText) view.findViewById(R.id.host_ip);
    etHostIP.setText(MemeOSC.getHostIPv4Address());
    etHostIP.setEnabled(false);

    etHostPort = (EditText) view.findViewById(R.id.host_port);
    etHostPort.setText(String.valueOf(((MainActivity) getActivity()).getSavedValue("HOST_PORT", 11316)));
    etHostPort.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if (!b) {
                InputMethodManager imm = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });
    etHostPort.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) {
            Log.d("DEBUG", "after text changed " + editable.toString());

            if (editable.toString().length() > 0) {
                ((MainActivity) getActivity()).autoSaveValue("HOST_PORT", Integer.valueOf(editable.toString()));
                testOSC.setHostPort(Integer.parseInt(editable.toString()));
                testOSC.initSocket();
            }
        }
    });

    btnTest = (Button) view.findViewById(R.id.remote_test);
    btnTest.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            layout.requestFocus();

            testOSC.setAddress("/meme/bridge", "/test");
            testOSC.setTypeTag("si");
            testOSC.addArgument(etRemoteIP.getText().toString());
            testOSC.addArgument(Integer.parseInt(etRemotePort.getText().toString()));
            testOSC.flushMessage();
        }
    });

    testOSC = new MemeOSC();
    testOSC.setRemoteIP(etRemoteIP.getText().toString());
    testOSC.setRemotePort(Integer.parseInt(etRemotePort.getText().toString()));
    testOSC.setHostPort(Integer.parseInt(etHostPort.getText().toString()));
    testOSC.initSocket();

    isShown = true;
    Thread rcvTestThread = new Thread(new ReceiveTestTRunnable());
    rcvTestThread.start();
}

From source file:nz.ac.otago.psyanlab.common.designer.program.operand.RenameOperandDialogueFragment.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Bundle args = getArguments();/*from  www  .ja v  a 2 s  .  c o  m*/
    if (args != null) {
        mOperandId = args.getLong(ARG_OPERAND_ID, -1);
    }

    if (mOperandId == -1) {
        throw new RuntimeException("Invalid operand id.");
    }

    mOperand = mCallbacks.getOperand(mOperandId);

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.dialogue_rename_variable, null);
    mName = (EditText) view.findViewById(R.id.name);
    mName.setText(mOperand.getName());

    // Thanks to serwus <http://stackoverflow.com/users/1598308/serwus>,
    // who posted at <http://stackoverflow.com/a/20325852>. Modified to
    // support unicode codepoints and validating first character of input.
    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            boolean keepOriginal = true;
            StringBuilder sb = new StringBuilder(end - start);

            int offset = 0;
            String s = source.toString();

            while (offset < s.length()) {
                final int codePoint = s.codePointAt(offset);
                if ((offset == 0 && isAllowedAsFirst(codePoint)) || (offset > 0 && isAllowed(codePoint))) {
                    sb.appendCodePoint(codePoint);
                } else {
                    keepOriginal = false;
                }
                offset += Character.charCount(codePoint);
            }

            if (keepOriginal)
                return null;
            else {
                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(sb);
                    TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                    return sp;
                } else {
                    return sb;
                }
            }
        }

        private boolean isAllowed(int codePoint) {
            return Character.isLetterOrDigit(codePoint);
        }

        private boolean isAllowedAsFirst(int codePoint) {
            return Character.isLetter(codePoint);
        }
    };

    mName.setFilters(new InputFilter[] { filter });

    // Build dialogue.
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(getString(R.string.title_rename_variable, mOperand.getName())).setView(view)
            .setPositiveButton(R.string.action_rename, mPositiveListener)
            .setNegativeButton(R.string.action_cancel, mNegativeListener);

    // Create the AlertDialog object and return it
    Dialog dialog = builder.create();
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    return dialog;
}

From source file:org.linphone.setup.WizardFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.setup_wizard, container, false);

    username = (EditText) view.findViewById(R.id.setup_username);
    ImageView usernameOkIV = (ImageView) view.findViewById(R.id.setup_username_ok);
    addXMLRPCUsernameHandler(username, usernameOkIV);

    inputFilterCharacters = new String(acceptedChars);
    if (getResources().getBoolean(R.bool.allow_only_phone_numbers_in_wizard)) {
        inputFilterCharacters = new String(acceptedCharsForPhoneNumbers);
    }/*ww w.j a  va 2 s.  c o  m*/
    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            if (end > start) {
                for (int index = start; index < end; index++) {
                    if (!inputFilterCharacters.contains(String.valueOf(source.charAt(index)))) {
                        return "";
                    }
                }
            }
            return null;
        }
    };
    username.setFilters(new InputFilter[] { filter });

    password = (EditText) view.findViewById(R.id.setup_password);
    passwordConfirm = (EditText) view.findViewById(R.id.setup_password_confirm);

    ImageView passwordOkIV = (ImageView) view.findViewById(R.id.setup_password_ok);
    addXMLRPCPasswordHandler(password, passwordOkIV);

    ImageView passwordConfirmOkIV = (ImageView) view.findViewById(R.id.setup_confirm_password_ok);
    addXMLRPCConfirmPasswordHandler(password, passwordConfirm, passwordConfirmOkIV);

    email = (EditText) view.findViewById(R.id.setup_email);
    ImageView emailOkIV = (ImageView) view.findViewById(R.id.setup_email_ok);
    addXMLRPCEmailHandler(email, emailOkIV);

    errorMessage = (TextView) view.findViewById(R.id.setup_error);

    createAccount = (ImageView) view.findViewById(R.id.setup_create);
    createAccount.setEnabled(false);
    createAccount.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    createAccount(getUsername(), password.getText().toString(), email.getText().toString(),
                            false);
                }
            });
            builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }
            });
            builder.setMessage(getString(R.string.setup_confirm_username).replace("%s", getUsername()));
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });

    if (getResources().getBoolean(R.bool.pre_fill_email_in_wizard)) {
        Account[] accounts = AccountManager.get(getActivity()).getAccountsByType("com.google");

        for (Account account : accounts) {
            if (isEmailCorrect(account.name)) {
                String possibleEmail = account.name;
                email.setText(possibleEmail);
                break;
            }
        }
    }

    return view;
}

From source file:org.linphone.setup.RegisterFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.setup_register, container, false);

    username = (EditText) view.findViewById(R.id.setup_username);
    ImageView usernameOkIV = (ImageView) view.findViewById(R.id.setup_username_ok);
    addXMLRPCUsernameHandler(username, usernameOkIV);

    inputFilterCharacters = new String(acceptedChars);
    if (getResources().getBoolean(R.bool.allow_only_phone_numbers_in_wizard)) {
        inputFilterCharacters = new String(acceptedCharsForPhoneNumbers);
    }//from  w w w . j  a  v  a2  s.c  o  m
    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            if (end > start) {
                for (int index = start; index < end; index++) {
                    if (!inputFilterCharacters.contains(String.valueOf(source.charAt(index)))) {
                        return "";
                    }
                }
            }
            return null;
        }
    };
    username.setFilters(new InputFilter[] { filter });

    password = (EditText) view.findViewById(R.id.setup_password);
    passwordConfirm = (EditText) view.findViewById(R.id.setup_password_confirm);

    ImageView passwordOkIV = (ImageView) view.findViewById(R.id.setup_password_ok);
    addXMLRPCPasswordHandler(password, passwordOkIV);

    ImageView passwordConfirmOkIV = (ImageView) view.findViewById(R.id.setup_confirm_password_ok);
    addXMLRPCConfirmPasswordHandler(password, passwordConfirm, passwordConfirmOkIV);

    email = (EditText) view.findViewById(R.id.setup_email);
    ImageView emailOkIV = (ImageView) view.findViewById(R.id.setup_email_ok);
    addXMLRPCEmailHandler(email, emailOkIV);

    errorMessage = (TextView) view.findViewById(R.id.setup_error);

    createAccount = (Button) view.findViewById(R.id.setup_create);
    createAccount.setEnabled(false);
    createAccount.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    createAccount(getUsername(), password.getText().toString(), email.getText().toString(),
                            false);
                }
            });
            builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }
            });
            builder.setMessage(getString(R.string.setup_confirm_username).replace("%s", getUsername()));
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    });

    if (getResources().getBoolean(R.bool.pre_fill_email_in_wizard)) {
        Account[] accounts = AccountManager.get(getActivity()).getAccountsByType("com.google");

        for (Account account : accounts) {
            if (isEmailCorrect(account.name)) {
                String possibleEmail = account.name;
                email.setText(possibleEmail);
                break;
            }
        }
    }

    return view;
}

From source file:com.awt.supark.EditCar.java

@Nullable
@Override/*from   w w  w  . j  a v  a  2  s.com*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.edit_car, container, false);

    addCarButton = (Button) view.findViewById(R.id.DoneButton);
    deleteButton = (Button) view.findViewById(R.id.DeleteButton);
    cancelButton = (Button) view.findViewById(R.id.cancelButton);
    carName = (EditText) view.findViewById(R.id.carName);
    carLicense = (EditText) view.findViewById(R.id.carLicense);
    txtCity = (TextView) view.findViewById(R.id.city);
    txtNum = (TextView) view.findViewById(R.id.number);
    radioNewSrb = (RadioButton) view.findViewById(R.id.radioNewSrb);
    radioGeneric = (RadioButton) view.findViewById(R.id.radioGeneric);
    radioLicenseGroup = (RadioGroup) view.findViewById(R.id.radioLicenseGroup);
    licensePlate = (LinearLayout) view.findViewById(R.id.licensePlate);
    licenseNum = "";
    context = getContext();

    // Setting the custom font
    Typeface licenseFont = Typeface.createFromAsset(getContext().getAssets(), "fonts/LicensePlate.ttf");
    txtCity.setTypeface(licenseFont);
    txtNum.setTypeface(licenseFont);

    db = SQLiteDatabase.openDatabase(getContext().getFilesDir().getPath() + "/carDB.db", null,
            SQLiteDatabase.CREATE_IF_NECESSARY);
    final Bundle b = getArguments();

    if (b.getInt("editid") != -1) {
        editid = b.getInt("editid");
        Cursor d = db.rawQuery("SELECT * FROM cars WHERE car_id = " + editid, null);
        d.moveToFirst();

        carName.setText(d.getString(d.getColumnIndex("car_name")));
        licenseNum = d.getString(d.getColumnIndex("car_license"));
        carLicense.setText(licenseNum);

        if (d.getInt(d.getColumnIndex("isgeneric")) == 0) {
            radioNewSrb.setChecked(true);
            radioGeneric.setChecked(false);
            radioListener();
        } else {
            radioGeneric.setChecked(true);
            radioNewSrb.setChecked(false);
            radioListener();
        }

        deleteButton.setVisibility(View.VISIBLE);
        if (isCarParked(editid)) {
            deleteButton.setEnabled(false);
        }
        TextView text = (TextView) view.findViewById(R.id.text1);
        text.setText(context.getResources().getString(R.string.edit_car));
        d.close();
    } else {
        radioNewSrb.setChecked(true);
        radioListener();
    }

    addCarButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (editid == -1) {
                addCar(v);
            } else {
                editCar(v);
            }
        }
    });

    deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showDeleteQuestionDialog("", getResources().getString(R.string.are_you_sure), v);
        }
    });

    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ((MainActivity) context).openCarFragment(null, true);
        }
    });

    // Filters the emojis and other unwanted characters
    filter = new InputFilter() {
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            for (int i = start; i < end; i++) {
                if (!Character.isLetterOrDigit(source.charAt(i))) {
                    return "";
                }
            }
            return null;
        }
    };
    carName.setFilters(new InputFilter[] { filter });
    //carLicense.setFilters(new InputFilter[] { filter });

    // License number filler
    carLicense.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) {
            licenseNum = charSequence.toString();
            updateLicensePlate(charSequence);
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

    radioLicenseGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            radioListener();
        }
    });

    return view;
}

From source file:org.deviceconnect.android.deviceplugin.hue.activity.fragment.HueFragment04.java

/**
 * Edit serial./*w  ww. j  ava2s  .  c  o  m*/
 */
private void editSerial() {
    final EditText editText = new EditText(getActivity());
    editText.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
                return true;
            }
            return false;
        }
    });
    AlertDialog dialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.frag04_serial_number_title)
            .setMessage(R.string.frag04_serial_number_message).setView(editText)
            .setPositiveButton(R.string.frag04_serial_ok, new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int whichButton) {
                    String serial = editText.getText().toString();
                    searchLightManually(serial);
                }
            }).setNegativeButton(R.string.frag04_serial_cancel, new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int whichButton) {
                }
            }).show();
    final Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
    positiveButton.setEnabled(false);

    // Input limit of the serial number
    InputFilter inputFilter = new InputFilter() {
        @Override
        public CharSequence filter(final CharSequence source, final int start, final int end,
                final Spanned dest, final int dstart, final int dend) {
            if (source.toString().matches("[0-9a-fA-F]+")) {
                return source;
            } else {
                return "";
            }
        }
    };
    InputFilter[] filters = new InputFilter[] { inputFilter, new InputFilter.LengthFilter(6) };
    editText.setFilters(filters);
    editText.addTextChangedListener(new TextWatcher() {
        @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) {
            positiveButton.setEnabled(editText.length() == 6);
        }

        @Override
        public void afterTextChanged(final Editable s) {
        }
    });
    editText.setHint(R.string.frag04_serial_number_hint);
}

From source file:org.chromium.chrome.browser.payments.ui.EditorView.java

/**
 * Builds the editor view.//from   ww  w.j  a va2s . c  o m
 *
 * @param activity        The activity on top of which the UI should be displayed.
 * @param observerForTest Optional event observer for testing.
 */
public EditorView(Activity activity, PaymentRequestObserverForTest observerForTest) {
    super(activity, R.style.FullscreenWhite);
    // Sets transparent background for animating content view.
    getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    mContext = activity;
    mObserverForTest = observerForTest;
    mHandler = new Handler();
    mEditorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                mDoneButton.performClick();
                return true;
            } else if (actionId == EditorInfo.IME_ACTION_NEXT) {
                View next = v.focusSearch(View.FOCUS_FORWARD);
                if (next != null) {
                    next.requestFocus();
                    return true;
                }
            }
            return false;
        }
    };

    mHalfRowMargin = activity.getResources().getDimensionPixelSize(R.dimen.payments_section_large_spacing);
    mFieldViews = new ArrayList<>();
    mEditableTextFields = new ArrayList<>();
    mDropdownFields = new ArrayList<>();

    final Pattern cardNumberPattern = Pattern.compile("^[\\d- ]*$");
    mCardNumberInputFilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            // Accept deletions.
            if (start == end)
                return null;

            // Accept digits, "-", and spaces.
            if (cardNumberPattern.matcher(source.subSequence(start, end)).matches()) {
                return null;
            }

            // Reject everything else.
            return "";
        }
    };

    mCardNumberFormatter = new CreditCardNumberFormattingTextWatcher();
    new AsyncTask<Void, Void, PhoneNumberFormattingTextWatcher>() {
        @Override
        protected PhoneNumberFormattingTextWatcher doInBackground(Void... unused) {
            return new PhoneNumberFormattingTextWatcher();
        }

        @Override
        protected void onPostExecute(PhoneNumberFormattingTextWatcher result) {
            mPhoneFormatter = result;
            if (mPhoneInput != null) {
                mPhoneInput.addTextChangedListener(mPhoneFormatter);
            }
        }
    }.execute();
}

From source file:org.noise_planet.noisecapture.CommentActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_comment);

    View mainView = findViewById(R.id.mainLayout);
    if (mainView != null) {
        mainView.setOnTouchListener(new MainOnTouchListener(this));
    }//from ww w.j a  va2 s .  c  o  m

    // Read record activity parameter
    // Use last record of no parameter provided
    this.measurementManager = new MeasurementManager(this);
    Intent intent = getIntent();
    // Read the last stored record
    List<Storage.Record> recordList = measurementManager.getRecords();
    if (intent != null && intent.hasExtra(COMMENT_RECORD_ID)) {
        record = measurementManager.getRecord(intent.getIntExtra(COMMENT_RECORD_ID, -1));
    } else {
        if (!recordList.isEmpty()) {
            record = recordList.get(0);
        } else {
            // Message for starting a record
            Toast.makeText(getApplicationContext(), getString(R.string.no_results), Toast.LENGTH_LONG).show();
            return;
        }
    }
    if (record != null) {
        View addPhoto = findViewById(R.id.btn_add_photo);
        addPhoto.setOnClickListener(new OnAddPhotoClickListener(this));
        View resultsBtn = findViewById(R.id.resultsBtn);
        resultsBtn.setOnClickListener(new OnGoToResultPage(this));
        View deleteBts = findViewById(R.id.deleteBtn);
        deleteBts.setOnClickListener(new OnDeleteMeasurement(this));
        TextView noisePartyTag = (TextView) findViewById(R.id.edit_noiseparty_tag);
        noisePartyTag.setEnabled(record.getUploadId().isEmpty());
        noisePartyTag.setFilters(new InputFilter[] { new InputFilter.AllCaps(), new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                // [^A-Za-z0-9_]
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = start; i < end; i++) {
                    char c = source.charAt(i);
                    if (Character.isLetterOrDigit(c) || c == '_') {
                        stringBuilder.append(c);
                    }
                }

                // keep original if unchanged or return swapped chars
                boolean modified = (stringBuilder.length() == end - start);
                return modified ? null : stringBuilder.toString();
            }
        } });
        if (record.getNoisePartyTag() == null) {
            // Read last stored NoiseParty id
            for (Storage.Record recordItem : recordList) {
                if (recordItem.getId() != record.getId()) {
                    if (recordItem.getNoisePartyTag() != null) {
                        noisePartyTag.setText(recordItem.getNoisePartyTag());
                    }
                    break;
                }
            }
        } else {
            noisePartyTag.setText(record.getNoisePartyTag());
        }
    }
    initDrawer(record != null ? record.getId() : null);
    SeekBar seekBar = (SeekBar) findViewById(R.id.pleasantness_slider);

    // Load stored user comment
    // Pleasantness and tags are read only if the record has been uploaded
    Map<String, Storage.TagInfo> tagToIndex = new HashMap<>(Storage.TAGS_INFO.length);
    for (Storage.TagInfo sysTag : Storage.TAGS_INFO) {
        tagToIndex.put(sysTag.name, sysTag);
    }

    View thumbnail = findViewById(R.id.image_thumbnail);
    thumbnail.setOnClickListener(new OnImageClickListener(this));
    if (record != null) {
        // Load selected tags
        for (String sysTag : measurementManager.getTags(record.getId())) {
            Storage.TagInfo tagInfo = tagToIndex.get(sysTag);
            if (tagInfo != null) {
                checkedTags.add(tagInfo.id);
            }
        }
        // Load description
        if (record.getDescription() != null) {
            TextView description = (TextView) findViewById(R.id.edit_description);
            description.setText(record.getDescription());
        }
        Integer pleasantness = record.getPleasantness();
        if (pleasantness != null) {
            seekBar.setProgress((int) (Math.round((pleasantness / 100.0) * seekBar.getMax())));
            seekBar.setThumb(
                    seekBar.getResources().getDrawable(R.drawable.seekguess_scrubber_control_normal_holo));
            userInputSeekBar.set(true);
        } else {
            seekBar.setThumb(
                    seekBar.getResources().getDrawable(R.drawable.seekguess_scrubber_control_disabled_holo));
        }
        photo_uri = record.getPhotoUri();
        // User can only update not uploaded data
        seekBar.setEnabled(record.getUploadId().isEmpty());
    } else {
        // Message for starting a record
        Toast.makeText(getApplicationContext(), getString(R.string.no_results), Toast.LENGTH_LONG).show();
    }
    thumbnailImageLayoutDoneObserver = new OnThumbnailImageLayoutDoneObserver(this);
    thumbnail.getViewTreeObserver().addOnGlobalLayoutListener(thumbnailImageLayoutDoneObserver);

    seekBar.setOnSeekBarChangeListener(new OnSeekBarUserInput(userInputSeekBar));
    // Fill tags grid
    Resources r = getResources();
    String[] tags = r.getStringArray(R.array.tags);
    // Append tags items
    for (Storage.TagInfo tagInfo : Storage.TAGS_INFO) {
        ViewGroup tagContainer = (ViewGroup) findViewById(tagInfo.location);
        if (tagContainer != null && tagInfo.id < tags.length) {
            addTag(tags[tagInfo.id], tagInfo.id, tagContainer,
                    tagInfo.color != -1 ? r.getColor(tagInfo.color) : -1);
        }
    }
}

From source file:org.akvo.rsr.up.UpdateEditorActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mUser = SettingsUtil.getAuthUser(this);
    nextLocalId = SettingsUtil.ReadInt(this, ConstantUtil.LOCAL_ID_KEY, -1);

    // find which update we are editing
    // null means create a new one
    Bundle extras = getIntent().getExtras();
    projectId = extras != null ? extras.getString(ConstantUtil.PROJECT_ID_KEY) : null;
    if (projectId == null) {
        DialogUtil.errorAlert(this, R.string.noproj_dialog_title, R.string.noproj_dialog_msg);
    }//from w w w  .j  a v a  2s.  co  m
    updateId = extras != null ? extras.getString(ConstantUtil.UPDATE_ID_KEY) : null;
    if (updateId == null) {
        updateId = savedInstanceState != null ? savedInstanceState.getString(ConstantUtil.UPDATE_ID_KEY) : null;
    }

    //Limit what we can write 
    InputFilter postFilter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                int dend) {
            boolean keepOriginal = true;
            StringBuilder sb = new StringBuilder(end - start);
            for (int i = start; i < end; i++) {
                char c = source.charAt(i);
                if (isCharAllowed(c)) // put your condition here
                    sb.append(c);
                else
                    keepOriginal = false;
            }
            if (keepOriginal)
                return null;
            else {
                if (source instanceof Spanned) {
                    SpannableString sp = new SpannableString(sb);
                    TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                    return sp;
                } else {
                    return sb;
                }
            }
        }

        private boolean isCharAllowed(char c) {
            //                    return !Character.isSurrogate(c); //From API 19
            return !(c >= 0xD800 && c <= 0xDFFF);
        }
    };

    // get the look
    setContentView(R.layout.activity_update_editor);
    // find the fields
    progressGroup = findViewById(R.id.sendprogress_group);
    uploadProgress = (ProgressBar) findViewById(R.id.sendProgressBar);
    projTitleLabel = (TextView) findViewById(R.id.projupd_edit_proj_title);
    projupdTitleCount = (TextView) findViewById(R.id.projupd_edit_titlecount);
    projupdTitleCount.setText(Integer.toString(TITLE_LENGTH));
    projupdTitleText = (EditText) findViewById(R.id.projupd_edit_title);
    projupdTitleText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(TITLE_LENGTH), postFilter });
    projupdTitleText.addTextChangedListener(new TextWatcher() {
        //Show count of remaining characters
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            projupdTitleCount.setText(String.valueOf(TITLE_LENGTH - s.length()));
        }

        public void afterTextChanged(Editable s) {
        }
    });
    projupdDescriptionText = (EditText) findViewById(R.id.projupd_edit_description);
    projupdDescriptionText.setFilters(new InputFilter[] { postFilter });
    projupdImage = (ImageView) findViewById(R.id.image_update_detail);
    photoAndToolsGroup = findViewById(R.id.image_with_tools);
    photoAddGroup = findViewById(R.id.photo_buttons);
    photoCaptionText = (EditText) findViewById(R.id.projupd_edit_photo_caption);
    photoCaptionText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(75), postFilter });
    photoCreditText = (EditText) findViewById(R.id.projupd_edit_photo_credit);
    photoCreditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(25), postFilter });

    positionGroup = findViewById(R.id.position_group);
    latField = (TextView) findViewById(R.id.latitude);
    lonField = (TextView) findViewById(R.id.longitude);
    eleField = (TextView) findViewById(R.id.elevation);
    accuracyField = (TextView) findViewById(R.id.gps_accuracy);
    searchingIndicator = (TextView) findViewById(R.id.gps_searching);
    gpsProgress = (ProgressBar) findViewById(R.id.progress_gps);

    // Activate buttons
    btnSubmit = (Button) findViewById(R.id.btn_send_update);
    btnSubmit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            sendUpdate();
        }
    });

    btnDraft = (Button) findViewById(R.id.btn_save_draft);
    btnDraft.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            saveAsDraft(true);
        }
    });

    btnTakePhoto = (Button) findViewById(R.id.btn_take_photo);
    btnTakePhoto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            // generate unique filename
            captureFilename = FileUtil.getExternalPhotoDir(UpdateEditorActivity.this) + File.separator
                    + "capture" + System.nanoTime() + ".jpg";
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(captureFilename)));
            startActivityForResult(takePictureIntent, photoRequest);
        }
    });

    btnAttachPhoto = (Button) findViewById(R.id.btn_attach_photo);
    btnAttachPhoto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
            photoPickerIntent.setType("image/*");
            startActivityForResult(photoPickerIntent, photoPick);
        }
    });

    btnDelPhoto = (Button) findViewById(R.id.btn_delete_photo);
    btnDelPhoto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // Forget image
            update.setThumbnailFilename(null);
            // TODO: delete image file if it was taken through this app?
            // Hide photo w tools
            showPhoto(false);
        }
    });

    btnRotRightPhoto = (Button) findViewById(R.id.btn_rotate_photo_r);
    btnRotRightPhoto.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            // Rotate image right
            rotatePhoto(true);
        }
    });

    btnGpsGeo = (Button) findViewById(R.id.btn_gps_position);
    btnGpsGeo.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onGetGPSClick(view);
        }
    });

    btnPhotoGeo = (Button) findViewById(R.id.btn_photo_position);
    btnPhotoGeo.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onGetPhotoLocationClick(view);
        }
    });

    dba = new RsrDbAdapter(this);
    dba.open();

    Project project = dba.findProject(projectId);
    projTitleLabel.setText(project.getTitle());

    if (updateId == null) { // create new
        update = new Update();
        update.setUuid(UUID.randomUUID().toString()); // should do sth
                                                      // better, especially
                                                      // if MAC address is
                                                      // avaliable
                                                      /*
                                                       * WifiManager wifiManager = (WifiManager)
                                                       * getSystemService(Context.WIFI_SERVICE); WifiInfo wInfo =
                                                       * wifiManager.getConnectionInfo(); String macAddress =
                                                       * wInfo.getMacAddress(); if (macAddress == null) txt_View.append(
                                                       * "MAC Address : " + macAddress + "\n" ); else txt_View.append(
                                                       * "MAC Address : " + macAddress + "\n" ); }
                                                       */
        update.setUserId(mUser.getId());
        update.setDate(new Date());
        editable = true;
    } else {
        update = dba.findUpdate(updateId);
        if (update == null) {
            DialogUtil.errorAlert(this, R.string.noupd_dialog_title, R.string.noupd2_dialog_msg);
        } else {
            // populate fields
            editable = update.getDraft(); // This should always be true with
                                          // the current UI flow - we go to
                                          // UpdateDetailActivity if it is sent
            if (update.getTitle().equals(TITLE_PLACEHOLDER)) {
                projupdTitleText.setText(""); //placeholder is just to satisfy db
            } else {
                projupdTitleText.setText(update.getTitle());
            }
            projupdDescriptionText.setText(update.getText());
            photoCaptionText.setText(update.getPhotoCaption());
            photoCreditText.setText(update.getPhotoCredit());
            latField.setText(update.getLatitude());
            lonField.setText(update.getLongitude());
            eleField.setText(update.getElevation());
            if (update.validLatLon()) {
                positionGroup.setVisibility(View.VISIBLE);
            }
            // show preexisting image
            if (update.getThumbnailFilename() != null) {
                // btnTakePhoto.setText(R.string.btncaption_rephoto);
                ThumbnailUtil.setPhotoFile(projupdImage, update.getThumbnailUrl(),
                        update.getThumbnailFilename(), null, null, false);
                photoLocation = FileUtil.exifLocation(update.getThumbnailFilename());
                showPhoto(true);
            }
        }
    }

    // register a listener for a completion and progress intents
    broadRec = new ResponseReceiver();
    IntentFilter f = new IntentFilter(ConstantUtil.UPDATES_SENT_ACTION);
    f.addAction(ConstantUtil.UPDATES_SENDPROGRESS_ACTION);
    LocalBroadcastManager.getInstance(this).registerReceiver(broadRec, f);

    enableChanges(editable);
    btnDraft.setVisibility(editable ? View.VISIBLE : View.GONE);
    btnSubmit.setVisibility(editable ? View.VISIBLE : View.GONE);
    // btnTakePhoto.setVisibility(editable?View.VISIBLE:View.GONE);

    // Show the Up button in the action bar.
    // setupActionBar();
}