android проверяет текстовое поле редактирования

#android #edit

#Android #Редактировать

Вопрос:

Хорошо, как я могу настроить проверки редактирования для текстового поля, чтобы ограничить ввод определенными символами и длиной.

Ниже приведено то, над чем я работал, но если курсор находится в первой позиции, и я нажимаю return, он разбивается

     final EditText editText1   = (EditText)findViewById(R.id.editText9);
    editText1.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT));
    editText1.setText("a");
    editText1.setTag(1);
    editText1.setId(idedittext1);
    editText1.setBackgroundColor(0xff66ff66);
    editText1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom)
    //linear1.addView(editText1);
    final String  matchCharacters = "abcdefghijklmnopqrstuvwxyz.";
    final CharSequence s_saved = "";
    editText1.addTextChangedListener(new TextWatcher()
    {

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

            System.out.println("------------------------------------------------------------");
            System.out.println("Entry: "   s   " "   s.length()   " "   start   " "   before   " "   count);

            if  (before == 1)
            {
                System.out.println("return");
            }


            if (s.length() > 4)
            {
                    System.out.println("onTextChanged >4 replaced : "   s   " "   start   " "   before   " "   count);
                    String replaceStr = s.toString().substring(0, s.length() - 1);
                    editText1.setText(replaceStr);
                    editText1.setSelection(s.length() - 1);
            }


            if (s.length() > 0 amp;amp; before != 1)
            {
                    Integer sfound = 0;
                    String sstr = s.toString();
                    char[] sArray = sstr.toCharArray();
                    char[] mArray = matchCharacters.toCharArray();
                    System.out.println("sarray-marray "   " "   sstr   "-"   matchCharacters);
                    for (char sc : sArray) {
                        System.out.println("It worked1 "   sc);
                        for (char mc : mArray) {
                            System.out.println("It worked2 "   " "   sc   "-"   mc);
                            if (sc == mc) {
                                //System.out.println("It worked!");
                                sfound = sfound   1;
                            } else {
                                //System.out.println("It did not work!");
                            }
                        }
                    }
                    System.out.println("slength-sfound "   " "   s.length()   "-"   sfound);
                    if (s.length() == sfound) {
                        System.out.println("MATCHED!");
                    } else {
                        System.out.println("NOMATCH!");
                        String replaceStr = s.toString().substring(0, s.length() - 1);
                        editText1.setText(replaceStr);
                        editText1.setSelection(s.length() - 1);


                        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
                        alertDialog.setTitle("Alert");
                        alertDialog.setMessage("Your can only enter the following characters: "   matchCharacters);
                        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                        alertDialog.show();
                    }
            }
        }
  

Любая помощь приветствуется.
Спасибо

Комментарии:

1. какие-либо журналы сбоев?

2. вы можете использовать метод setMaxLines(5) , чтобы ограничить количество строк для EditText

Ответ №1:

Чтобы ограничить длину редактируемого текста

 <EditText
    android:id="@ id/edit_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLength="10"/>
  

Чтобы предотвратить ввод определенного символа

    final EditText editText = (EditText) findViewById(R.id.edit_text);
   final String matchCharacters  = "aeiou";
   editText.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) {
           String text = String.valueOf(editText.getText());
           boolean edited = false;
           for(int i=0; i<matchCharacters.length(); i  ){
               char toPrevent = matchCharacters.charAt(i);
               if(text.indexOf(toPrevent) < 0){
                   continue;
               }

               text = text.replace(String.valueOf(toPrevent), "");
               edited = true;
           }

           if(edited){
               editText.setText(text);
           }
       }
    });