Android-Obsługa "Enter" w edytorze tekstu

Zastanawiam się, czy istnieje sposób, aby poradzić sobie z naciśnięciem Enter Podczas wpisywania EditText, coś w rodzaju zdarzenia ONSUBMIT HTML.

Zastanawiam się również, czy istnieje sposób na manipulowanie wirtualną klawiaturą w taki sposób, że przycisk "Gotowe" jest oznaczony jako coś innego (na przykład "Go") i wykonuje określoną akcję po kliknięciu (ponownie, jak onSubmit).

Author: MiguelHincapieC, 2009-09-29

20 answers

Zastanawiam się, czy jest sposób na obsługi użytkownika naciskając Enter podczas wpisując EditText, coś w rodzaju Zdarzenie ONSUBMIT HTML.

Tak.

Również zastanawiam się, czy istnieje sposób, aby manipuluj wirtualną klawiaturą w taki sposób, aby przycisk "Gotowe" był oznaczone czymś innym (np. "Go") i wykonuje określoną czynność po kliknięciu (ponownie, jak onSubmit).

Również tak.

Będziesz chciał spojrzeć na android:imeActionId oraz android:imeOptions atrybuty, plus setOnEditorActionListener() metoda, wszystko na TextView.

Aby zmienić tekst przycisku "Gotowe" na niestandardowy ciąg znaków, użyj:

mEditText.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);
 334
Author: CommonsWare,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-08 15:05:00

Oto co zrobisz. Jest również ukryty w przykładowym kodzie dewelopera Androida "Bluetooth Chat". Zastąp pogrubione części z napisem "example" własnymi zmiennymi i metodami.

Najpierw zaimportuj to, czego potrzebujesz do głównej aktywności, gdzie chcesz, aby przycisk return zrobił coś specjalnego:

import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.view.KeyEvent;

Teraz stwórz zmienną typu TextView.OnEditorActionListener dla Twojego klucza zwrotnego (tutaj używam exampleListener);

TextView.OnEditorActionListener exampleListener = new TextView.OnEditorActionListener(){

Następnie musisz powiedzieć słuchacz dwie rzeczy o tym, co zrobić, gdy przycisk powrotu jest wciśnięty. Musi wiedzieć, o czym mówimy (tutaj używam exampleView), a następnie musi wiedzieć, co zrobić, gdy klawisz Enter Jest wciśnięty (tutaj, example_confirm () ). Jeśli jest to ostatni lub jedyny EditText w Twojej aktywności, powinien zrobić to samo, co metoda onclick dla przycisku Submit (lub OK, Confirm, Send, Save, itp.).

public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
   if (actionId == EditorInfo.IME_NULL  
      && event.getAction() == KeyEvent.ACTION_DOWN) { 
      example_confirm();//match this behavior to your 'Send' (or Confirm) button
   }
   return true;
}

Na koniec ustaw słuchacza (najprawdopodobniej w Twoim metoda onCreate);

exampleView.setOnEditorActionListener(exampleListener);
 204
Author: Chad Hedgcock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-05 07:37:03
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_ENTER)) {
          // Perform action on key press
          Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
          return true;
        }
        return false;
    }
});
 201
Author: Jarod DY Law,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-22 07:46:14

Klawiatury sprzętowe zawsze zwracają zdarzenia enter, ale klawiatury programowe zwracają różne identyfikatory akcji i Null w edytorach pojedynczych linii. Kod ten odpowiada za każdym razem, gdy użytkownik naciśnie enter w edytorze, na który został ustawiony ten słuchacz, niezależnie od typu edytora lub klawiatury.

import android.view.inputmethod.EditorInfo;
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;

listener=new TextView.OnEditorActionListener() {
  @Override
  public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
    if (event==null) {
      if (actionId==EditorInfo.IME_ACTION_DONE);
      // Capture soft enters in a singleLine EditText that is the last EditText.
      else if (actionId==EditorInfo.IME_ACTION_NEXT);
      // Capture soft enters in other singleLine EditTexts
      else return false;  // Let system handle all other null KeyEvents
    }
    else if (actionId==EditorInfo.IME_NULL) { 
    // Capture most soft enters in multi-line EditTexts and all hard enters.
    // They supply a zero actionId and a valid KeyEvent rather than
    // a non-zero actionId and a null event like the previous cases.
      if (event.getAction()==KeyEvent.ACTION_DOWN); 
      // We capture the event when key is first pressed.
      else  return true;   // We consume the event when the key is released.  
    }
    else  return false; 
    // We let the system handle it when the listener
    // is triggered by something that wasn't an enter.


    // Code from this point on will execute whenever the user
    // presses enter in an attached view, regardless of position, 
    // keyboard, or singleLine status.

    if (view==multiLineEditText)  multiLineEditText.setText("You pressed enter");
    if (view==singleLineEditText)  singleLineEditText.setText("You pressed next");
    if (view==lastSingleLineEditText)  lastSingleLineEditText.setText("You pressed done");
    return true;   // Consume the event
  }
};

Domyślny wygląd klawisza enter w singleLine = false daje zagiętą strzałkę enter klawiatura. Gdy singleLine = true w ostatnim EditText klucz mówi zrobione, a na EditText przed nim mówi Następny. Domyślnie to zachowanie jest spójne we wszystkich emulatorach vanilla, android i google. Atrybut scrollHorizontal nie robi żadnej różnicy. Test null jest ważny, ponieważ odpowiedź telefonów na soft wchodzi jest pozostawiona producentowi, a nawet w emulatorach, emulatory vanilla Level 16 reagują na długie soft wchodzi w multi-line i scrollHorizontal EditText z actionId NEXT I null dla zdarzenia.

 32
Author: earlcasper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-07 19:18:37

Wiem, że to ma rok, ale właśnie odkryłem, że działa idealnie dla EditText.

EditText textin = (EditText) findViewById(R.id.editText1);
textin.setInputType(InputType.TYPE_CLASS_TEXT);

Uniemożliwia wszystko poza tekstem i spacją. Nie mogłem zakładkę, "return" ("\n"), lub cokolwiek.

 19
Author: Newbie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-03 13:18:11

Jako dodatek do odpowiedzi Chada (która działała prawie idealnie dla mnie), stwierdziłem, że muszę dodać sprawdzenie typu akcji KeyEvent, aby zapobiec dwukrotnemu wykonaniu kodu (raz na zdarzeniu key-up i raz na key-down).

if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)
{
    // your code here
}

Zobacz http://developer.android.com/reference/android/view/KeyEvent.html dla informacji o powtarzających się zdarzeniach akcji (przytrzymując klawisz enter) itd.

 15
Author: kermitology,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-23 15:29:45

Miałem podobny cel. Chciałem rozwiązać naciśnięcie klawisza "Enter" na klawiaturze (którą chciałem dostosować) w AutoCompleteTextView, który rozszerza TextView. Próbowałem różnych rozwiązań z góry i wydawało się, że działają. Ale doświadczyłem pewnych problemów, gdy przełączyłem typ wejścia na moim urządzeniu (Nexus 4 z ROM AOKP) z SwiftKey 3 (gdzie działało idealnie) na standardową klawiaturę Android (gdzie zamiast obsługiwać mój kod od słuchacza, nowa linia została wprowadzona po naciśnięcie klawisza "Enter". Zajęło mi to trochę czasu, aby poradzić sobie z tym problemem, ale nie wiem, czy będzie działać w każdych okolicznościach, bez względu na to, jakiego typu wejścia używasz.

Oto moje rozwiązanie:

Ustaw atrybut input type W TextView w xml na "text":

android:inputType="text"

Dostosuj Etykietę klawisza "Enter"na klawiaturze:

myTextView.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);

Ustaw OnEditorActionListener do TextView:

myTextView.setOnEditorActionListener(new OnEditorActionListener()
{
    @Override
    public boolean onEditorAction(TextView v, int actionId,
        KeyEvent event)
    {
    boolean handled = false;
    if (actionId == KeyEvent.KEYCODE_ENTER)
    {
        // Handle pressing "Enter" key here

        handled = true;
    }
    return handled;
    }
});

Mam nadzieję, że pomoże to innym uniknąć problemów, które miałem, ponieważ prawie doprowadzali mnie do szału.

 14
Author: kaolick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-20 14:57:37

Ta strona dokładnie opisuje, jak to zrobić.

Https://developer.android.com/training/keyboard-input/style.html

Ustaw android: imeOptions , a następnie sprawdź actionId w onEditorAction. Jeśli więc ustawisz imeOptions na 'actionDone', to sprawdzisz ' actionId = = EditorInfo.IME_ACTION_DONE ' w onEditorAction. Upewnij się również, że ustawiłeś android: inputType.

Oto EditText z przykładu linked powyżej:

<EditText
    android:id="@+id/search"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search_hint"
    android:inputType="text"
    android:imeOptions="actionSend" />

Można również ustawić to programowo za pomocą funkcji setImeOptions(int). Oto OnEditorActionListener z powyższego przykładu:

EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendMessage();
            handled = true;
        }
        return handled;
    }
});
 11
Author: Mike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-04 17:35:49

W xml Dodaj atrybut imeOptions do editText

<EditText
    android:id="@+id/edittext_additem"
    ...
    android:imeOptions="actionDone"
    />

Następnie w kodzie Java dodaj oneditoractionlistener do tego samego EditText

mAddItemEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_DONE){
                //do stuff
                return true;
            }
            return false;
        }
    });

Oto Wyjaśnienie- ImeOptions = actionDone przypisze" actionDone " do klawisza Enter. Klawisz Enter na klawiaturze zmieni się z "Enter " na"gotowe". Więc po naciśnięciu klawisza Enter, wywoła tę akcję, a tym samym obsłużysz ją.

 10
Author: Akshayraj Kore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-23 15:07:43

Ty też możesz to zrobić..

editText.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getKeyCode() ==       KeyEvent.KEYCODE_ENTER) 
                {
                    Log.i("event", "captured");

                    return false;
                } 

            return false;
        }
    });
 7
Author: Xar E Ahmer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-21 12:27:18
     password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
                submit.performClick();
                return true;
            }
            return false;
        }
    });

Działa bardzo dobrze dla mnie
Dodatkowo ukryj klawiaturę

 5
Author: V. Kalyuzhnyu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-07 15:20:57

Najpierw musisz ustawić EditText listen, aby nacisnąć klawisz

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

    // Set the EditText listens to key press
    EditText edittextproductnumber = (EditText) findViewById(R.id.editTextproductnumber);
    edittextproductnumber.setOnKeyListener(this);

}

Po Drugie, zdefiniuj zdarzenie po naciśnięciu klawisza, na przykład zdarzenie, aby ustawić tekst TextView:

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub

 // Listen to "Enter" key press
 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
 {
     TextView textviewmessage = (TextView) findViewById(R.id.textViewmessage);
     textviewmessage.setText("You hit 'Enter' key");
     return true;
 }

return false;   

}

I na koniec, nie zapomnij zaimportować EditText, TextView, OnKeyListener, KeyEvent na górze:

import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
 3
Author: LifeiSHot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-08 03:26:31

Praca perfekcyjna

public class MainActivity extends AppCompatActivity {  
TextView t;
Button b;
EditText e;

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

    b = (Button) findViewById(R.id.b);
    e = (EditText) findViewById(R.id.e);

    e.addTextChangedListener(new TextWatcher() {

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

            if (before == 0 && count == 1 && s.charAt(start) == '\n') {

                b.performClick();
                e.getText().replace(start, start + 1, ""); //remove the <enter>
            }

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

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            b.setText("ok");

        }
    });
}

}

Praca perfekcyjna

 3
Author: Domi mtz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-01 21:45:53

To działa dobrze na telefonach LG z Androidem. Uniemożliwia interpretację ENTER i innych znaków specjalnych jako znaków normalnych. Next lub Done przycisk pojawia się automatycznie i ENTER działa zgodnie z oczekiwaniami.

edit.setInputType(InputType.TYPE_CLASS_TEXT);
 3
Author: Milan Švec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-15 04:48:21

To powinno zadziałać

input.addTextChangedListener(new TextWatcher() {

           @Override
           public void afterTextChanged(Editable s) {}

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

           @Override    
           public void onTextChanged(CharSequence s, int start,
             int before, int count) {
               if( -1 != input.getText().toString().indexOf( "\n" ) ){
                   input.setText("Enter was pressed!");
                    }
           }
          });
 2
Author: ORY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-02 19:03:45

Niezawodnym sposobem odpowiedzi na w EditText jest Texttwatcher , LocalBroadcastManager i BroadcastReceiver . Aby użyć menedżera LocalBroadcastManager, musisz dodać bibliotekę V4 . Używam tutoriala na vogella.com: 7.3 "lokalne zdarzenia transmisji z LocalBroadcastManager" ze względu na kompletny, zwięzły przykład kodu. W onTextChanged before jest indeksem końca zmiany przed Zmień>;minus start. Gdy w TextWatcher wątek UI jest zajęty aktualizowaniem EditText ' s editable, WIĘC WYSYŁAMY intencję, aby obudzić BroadcastReceiver, gdy wątek UI zakończy aktualizację editText.

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
//in onCreate:
editText.addTextChangedListener(new TextWatcher() {
  public void onTextChanged
  (CharSequence s, int start, int before, int count) {
    //check if exactly one char was added and it was an <enter>
    if (before==0 && count==1 && s.charAt(start)=='\n') {
    Intent intent=new Intent("enter")
    Integer startInteger=new Integer(start);
    intent.putExtra("Start", startInteger.toString()); // Add data
    mySendBroadcast(intent);
//in the BroadcastReceiver's onReceive:
int start=Integer.parseInt(intent.getStringExtra("Start"));
editText.getText().replace(start, start+1,""); //remove the <enter>
//respond to the <enter> here
 1
Author: earlcasper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-21 22:17:27

InputType na polu tekstowym musi być "text", aby to, co CommonsWare powiedział działać. Po prostu próbowałem tego wszystkiego, żadnego inputType przed próbą i nic nie działało, Enter rejestrował się jako soft enter. Po inputType = text wszystko, łącznie z setImeLabel działało.

 1
Author: Odaym,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-07 14:56:35
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId != 0 || event.getAction() == KeyEvent.ACTION_DOWN) {
                // Action
                return true;
            } else {
                return false;
            }
        }
    });

Xml

<EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/password"
        android:imeOptions="actionGo|flagNoFullscreen"
        android:inputType="textPassword"
        android:maxLines="1" />
 1
Author: kreker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-09 17:39:49

Odpowiedź Jareda Law ' A działa jak urok dla mnie.

Właśnie dodałem te depencendy:

import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
 1
Author: Jacky Supit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-08 10:29:37

Oto prosta statyczna funkcja, którą możesz wrzucić do klasy Utils lub Keyboards, która wykona kod, gdy użytkownik naciśnie klawisz return na klawiaturze sprzętowej lub programowej. Jest to zmodyfikowana wersja doskonałej odpowiedzi @earlcasper

 /**
 * Return a TextView.OnEditorActionListener that will execute code when an enter is pressed on
 * the keyboard.<br>
 * <code>
 *     myTextView.setOnEditorActionListener(Keyboards.onEnterEditorActionListener(new Runnable()->{
 *         Toast.makeText(context,"Enter Pressed",Toast.LENGTH_SHORT).show();
 *     }));
 * </code>
 * @param doOnEnter A Runnable for what to do when the user hits enter
 * @return the TextView.OnEditorActionListener
 */
public static TextView.OnEditorActionListener onEnterEditorActionListener(final Runnable doOnEnter){
    return (__, actionId, event) -> {
        if (event==null) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // Capture soft enters in a singleLine EditText that is the last EditText.
                doOnEnter.run();
                return true;
            } else if (actionId==EditorInfo.IME_ACTION_NEXT) {
                // Capture soft enters in other singleLine EditTexts
                doOnEnter.run();
                return true;
            } else {
                return false;  // Let system handle all other null KeyEvents
            }
        } else if (actionId==EditorInfo.IME_NULL) {
            // Capture most soft enters in multi-line EditTexts and all hard enters.
            // They supply a zero actionId and a valid KeyEvent rather than
            // a non-zero actionId and a null event like the previous cases.
            if (event.getAction()==KeyEvent.ACTION_DOWN) {
                // We capture the event when key is first pressed.
                return true;
            } else {
                doOnEnter.run();
                return true;   // We consume the event when the key is released.
            }
        } else {
            // We let the system handle it when the listener
            // is triggered by something that wasn't an enter.
            return false;
        }
    };
}
 0
Author: JohnnyLambada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-12 18:31:04