Domanda

Mi chiedo se c'è un modo per gestire l'utente preme Invio durante la digitazione in un EditText, qualcosa come l'evento onSubmit HTML.

chiedendosi anche se c'è un modo per manipolare la tastiera virtuale in modo tale che il pulsante "Done" viene etichettato qualcos'altro (ad esempio "Go") ed esegue una determinata azione se cliccata (ancora una volta, come onSubmit).

È stato utile?

Soluzione

  

Mi chiedo se c'è un modo per   gestire l'utente preme Invio , mentre   digitando in un EditText, qualcosa di simile   l'evento onSubmit HTML.

Sì.

  

chiedendosi anche se c'è un modo per   manipolare la tastiera virtuale   modo che il pulsante "Done" è   qualcosa etichettata altro (ad esempio   "Go") ed esegue una determinata azione   quando si fa clic (ancora una volta, come onsubmit).

Anche sì.

Hai voglia di guardare il android:imeActionId e android:imeOptions attributi, più il metodo setOnEditorActionListener() , tutti su TextView.

Per modificare il testo del pulsante "Done" per una stringa personalizzato, utilizzare:

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

Altri suggerimenti

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;
    }
});

Ecco quello che fate. E 'anche nascosto nel codice di esempio per gli sviluppatori di Android 'Bluetooth Chat'. Sostituire le parti in grassetto che dire "esempio" con le proprie variabili e metodi.

In primo luogo, importare quello che ti serve in attività principale dove si desidera che il pulsante di ritorno per fare qualcosa di speciale:

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

Ora, fare una variabile di tipo TextView.OnEditorActionListener per la chiave di ritorno (qui io uso exampleListener );

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

allora avete bisogno di dire a chi ascolta due cose su cosa fare quando si preme il pulsante di ritorno. Ha bisogno di sapere che cosa EditText stiamo parlando (qui io uso exampleView ), e quindi ha bisogno di sapere cosa fare quando la pressione del tasto ENTER (qui, example_confirm () ). Se questo è l'ultimo o unico EditText nella vostra attività, si dovrebbe fare la stessa cosa come il metodo onClick per la Submit (o OK, confermare, Invia, Salva, ecc) pulsante.

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;
}

Infine, impostare l'ascoltatore (molto probabilmente nel metodo onCreate);

exampleView.setOnEditorActionListener(exampleListener);

tastiere hardware producono sempre inserire gli eventi, ma le tastiere software restituiscono diversi actionIDs e nulli in SingleLine EditTexts. Questo codice risponde ogni volta che l'utente preme entrano in un EditText quali l'ascoltatore è stato impostato, indipendentemente EditText o tipo di tastiera.

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
  }
};

L'aspetto predefinito del tasto Invio in SingleLine = false dà una freccia piegata entrare tastiera. Quando SingleLine = true nell'ultimo EditText la chiave dice DONE, e sulle EditTexts prima di esso si dice NEXT. Per impostazione predefinita, questo comportamento è coerente in tutte vaniglia, Android, e Google emulatori. L'attributo scrollHorizontal non fa alcuna differenza. La prova nulla è importante, perché la risposta dei telefoni a morbida entra è lasciata al produttore e anche nei emulatori, il livello di vaniglia 16 emulatori rispondono a lungo morbida entra in multi-linea e scrollHorizontal EditTexts con un'ActionID di NEXT e un nullo per l'evento.

So che questo è un anno, ma ho appena scoperto questo funziona perfettamente per un EditText.

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

Si impedisce qualsiasi cosa ma il testo e lo spazio. Non potevo scheda, "ritorno" ( "\ n"), o altro.

Questa pagina descrive esattamente come fare questo.

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

Android: imeOptions poi basta controllare il ActionID in onEditorAction. Quindi, se si imposta imeOptions a 'actionDone' allora si sarebbe verificare la presenza di 'ActionID == EditorInfo.IME_ACTION_DONE' in onEditorAction. Inoltre, assicurarsi di impostare l'androide:. InputType

Ecco l'EditText dall'esempio linkato sopra:

<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" />

È inoltre possibile impostare questa programmazione utilizzando i setImeOptions (int) funzione. Ecco l'OnEditorActionListener dall'esempio linkato sopra:

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;
    }
});

Proprio come un addendum alla risposta del Ciad (che ha funzionato quasi perfettamente per me), ho scoperto che avevo bisogno di aggiungere un controllo sul tipo di azione KeyEvent per evitare che il mio codice in esecuzione due volte (una volta il tasto-up e una volta sul evento chiave-down).

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

http://developer.android.com/reference/android/view /KeyEvent.html per informazioni su eventi ricorrenti di azione (tenendo premuto il tasto invio), ecc.

ho avuto uno scopo simile. Ho voluto per risolvere premendo il tasto "Invio" sulla tastiera (che ho voluto personalizzare) in un AutoCompleteTextView che si estende TextView. Ho provato diverse soluzioni dall'alto e che sembrava funzionare. MA sperimentato alcuni problemi quando sono passato il tipo di ingresso sul dispositivo (Nexus 4 con AOKP ROM) da SwiftKey 3 (dove ha funzionato perfettamente) alla tastiera Android standard (dove invece di movimentazione mio codice dall'ascoltatore, una nuova linea era entrato dopo aver premuto il tasto "Enter". mi c'è voluto un po 'per gestire questo problema, ma non so se funzionerà in tutte le circostanze, non importa che tipo di ingresso si utilizza.

Quindi, ecco la mia soluzione:

Impostare l'attributo tipo di ingresso del TextView in XML per "testo":

android:inputType="text"

Personalizza l'etichetta del tasto "Invio" sulla tastiera:

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

Impostare un OnEditorActionListener al TextView:

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

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

Spero che questo possa aiutare gli altri per evitare i problemi che ho avuto, perché quasi mi ha spinto noci.

Nel vostro XML, aggiungere i imeOptions attribuiscono al EditText

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

Poi, nel codice Java, aggiungere l'OnEditorActionListener allo stesso 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;
        }
    });

Questa è l'explanation- L'imeOptions = actionDone assegnerà "actionDone" al tasto ENTER. L'enterkey nella tastiera cambierà da "Enter" per "Fatto". Così, quando si preme ENTER chiave, innescherà questa azione e quindi si tratterà di esso.

Si può anche farlo ..

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;
        }
    });
     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;
        }
    });

funziona molto bene per me
Inoltre nascondere i tasti

perfettamente funzionante

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");

        }
    });
}

}

perfettamente funzionante

In primo luogo, è necessario impostare EditText ascoltare premere il tasto

@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);

}

In secondo luogo, definire l'evento sulla pressione di un tasto, per esempio, evento per impostare il testo di 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;   

}

E, infine, non dimenticate di importare EditText, TextView, OnKeyListener, KeyEvent in alto:

import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
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" />

Questo dovrebbe funzionare

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!");
                    }
           }
          });

Questo funziona bene sui telefoni LG Android. Previene ENTER e altri caratteri speciali necessari per essere interpretati come carattere normale. Next o il pulsante Done compare automaticamente e ENTER funziona come previsto.

edit.setInputType(InputType.TYPE_CLASS_TEXT);

Ecco una funzione statica semplice che si può buttare nel vostro Utils o classe Keyboards che verrà eseguito il codice quando l'utente preme il tasto Invio su una tastiera hardware o software. Si tratta di una versione modificata di risposta eccellente @ di 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;
        }
    };
}

InputType sul campo di testo deve essere text in modo che quello che CommonsWare detto di lavorare. Appena provato tutto questo, non InputType prima del processo e niente ha funzionato, inserire mantenuto la registrazione come software INVIO. Dopo inputType = text, tutto compreso il setImeLabel funzionato.

Esempio: android:inputType="text"

   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;
        }
    });

Inserisci il codice nel vostro editor in modo che possa importare moduli necessari.

 query.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if(actionId == EditorInfo.IME_ACTION_DONE
                || actionId == EditorInfo.IME_ACTION_DONE
                    || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                        || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {

                // Put your function here ---!

                return true;

            }
            return false;
        }
    });

Un modo affidabile per rispondere a un in un EditText è con un TextWatcher , un LocalBroadcastManager , e un BroadcastReceiver . È necessario aggiungere il v4 libreria di supporto di utilizzare la LocalBroadcastManager. Io uso il tutorial a vogella.com : 7.3 "eventi broadcast locali con LocalBroadcastManager" a causa del suo codice completo dell'esempio conciso. In OnTextChanged prima è l'indice della fine del cambiamento prima del cambio >; meno START. Quando, nel TextWatcher thread dell'interfaccia utente è occupato l'aggiornamento di EditText modificabile, in modo da inviare l'intento di svegliare la BroadcastReceiver quando il thread UI è fatto l'aggiornamento 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

Aggiungi questi depencendy, e dovrebbe funzionare:

import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

Questa domanda non ha ancora ricevuto alcuna risposta con butterknife

DISPOSIZIONE XML

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/some_input_hint">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/textinput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionSend"
            android:inputType="text|textCapSentences|textAutoComplete|textAutoCorrect"/>
    </android.support.design.widget.TextInputLayout>

JAVA APP

@OnEditorAction(R.id.textinput)
boolean onEditorAction(int actionId, KeyEvent key){
    boolean handled = false;
    if (actionId == EditorInfo.IME_ACTION_SEND || (key.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
        //do whatever you want
        handled = true;
    }
    return handled;
}

Kotlin

editTextVar?.setOnKeyListener { v, keyCode, event ->
            if((event.action == KeyEvent.ACTION_DOWN)
                && (event.keyCode == KeyEvent.KEYCODE_ENTER)){
                //Do something, such as loadJob()
                loadJob()
                return@setOnKeyListener true
            }

            false
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top