Android enter key listener - android

Can someone help me with a softkeyboard enter key listener?
I need a enter key listener like a button listener that would have a few editext listeners inside
like this
enterkey.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(editext1.getText().toString().equalsIgnoreCase("test1")) {
button3.performClick();
}
if(editext1.getText().toString().equalsIgnoreCase("test2")) {
button4.performClick();
}
}
);
I also need to know if something like this is correct?
if(editext1.getText().toString().equals.null)) {
testwrong.setText("Wrong");
I have now tried using this code but keep getting a null value when I hit enter?
Can anyone suggest a solution to avoid this?
editext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
if ("test1".equalsIgnoreCase(anstext.getText().toString())) {
but4.performClick();
}
} else if ("test2".equalsIgnoreCase(editext.getText().toString())) {
but5.performClick();
}
if ("test5".equalsIgnoreCase(editext.getText().toString())) {
but6.performClick();
}
if ("test7".equalsIgnoreCase(editext.getText().toString())) {
but7.performClick();
}
if (editext.getText().toString() != null) {
testwrong.seText("wrong");
}
return true;
}
});

In your EditText you should specify keyboard action using imeOptions.
<EditText
android:id="#+id/query"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:imeOptions="actionGo"
android:inputType="text" />
And in your Activity's class:
EditText editText = (EditText) findViewById(R.id.query);
editText.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
return true;
}
return false;
}
});

If you want to catch user press Enter register onKeyListener on your Edittext
yourEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode==KeyEvent.KEYCODE_ENTER) { //Whenever you got user click enter. Get text in edittext and check it equal test1. If it's true do your code in listenerevent of button3
if("test1".equals(edt.getText().toString())) {
//paste your code in button3 listener here
}
}
}
)
This part is wrong.
if(editext1.getText().toString().equals.null)) {
testwrong.setText("Wrong");
you should change to
if (editext1.getText().toString() != null && !editext1.getText().toString().isEmpty()) {
// doSomething
}

you can use this to listen to keyboard events
http://developer.android.com/reference/android/inputmethodservice/KeyboardView.OnKeyboardActionListener.html

Related

OnKey Event For One EditText Is Working For Two EditTexts, How To Fix This?

A beginner here, I am looking to make a simple app in which there are 4 sequential EditTexts, and as soon as the first EditText is completed and the user presses 'enter', the focus is automatically taken to the next EditText and the first EditText disappears.
I have used an 'onKey listener'. However, whenever the enter key is pressed for the first EditText, both the first and second EditText fields disappear.
Here is the code
public class MainActivity extends AppCompatActivity {
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText ko = findViewById(R.id.one);
final EditText ma = findViewById(R.id.two);
final EditText ko1 = findViewById(R.id.three);
final EditText xa = findViewById(R.id.four);
final TextView te = findViewById(R.id.ko);
ko.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER) {
ko.setVisibility(View.INVISIBLE);
ma.requestFocus();
}
return false;
}
});
ma.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent k) {
if(i == KeyEvent.KEYCODE_ENTER) {
ma.setVisibility(View.INVISIBLE);
ko1.requestFocus();
}
return false;
}
});
ko1.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent t) {
if(i == KeyEvent.KEYCODE_ENTER) {
ko1.setVisibility(View.INVISIBLE);
xa.requestFocus();
}
return false;
}
});
}
public void onClick(View v){
EditText ko = findViewById(R.id.one);
EditText ma = findViewById(R.id.two);
EditText ko1 = findViewById(R.id.three);
EditText xa = findViewById(R.id.four);
String t = ko.getText().toString();
String u = ma.getText().toString();
String x = ko1.getText().toString();
String w = xa.getText().toString();
String total = t +" "+ u +" "+x + " " +w;
Toast.makeText(this, total,Toast.LENGTH_LONG).show();
}
}
The event will continue to bubble up the container chain if you return false
Returns True if the listener has consumed the event, false otherwise.
ko.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER) {
ko.setVisibility(View.INVISIBLE);
ma.requestFocus();
}
return true;//change this line and all its occurances
}
});
Return true after requesting focus. Refer View.OnKeyListener
True if the listener has consumed the event, false otherwise.
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER) {
ko.setVisibility(View.INVISIBLE);
ma.requestFocus();
return true; // this will consume the Enter event
}
return false;
}

Edittext Focus and click

I have Two EditTexts. I want On First EditTexts click clear the second and on second edittext click clear the first one. So I have tried OnClickListener and OnTouchListener. But it is not working properly.
et_email.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!(et_email.getText().toString().equalsIgnoreCase("") && et_mobile.getText().toString().equalsIgnoreCase(""))) {
if (MotionEvent.ACTION_UP == event.getAction()) {
et_mobile.setText("");
et_mobile.setFocusableInTouchMode(true);
et_mobile.setFocusable(true);
et_mobile.requestFocus();
}
return true; // return is important...
} else
return false;
}
});
et_mobile.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!(et_email.getText().toString().equalsIgnoreCase("") && et_mobile.getText().toString().equalsIgnoreCase(""))) {
if (MotionEvent.ACTION_UP == event.getAction()) {
et_email.setText("");
et_mobile.setFocusableInTouchMode(true);
et_mobile.setFocusable(true);
et_mobile.requestFocus();
}
return true; // return is important...
}
else
return false;
}
});
But the problem is Focus is not setting on first touch and while clicking and unable to clear EditText.
First add this to your Edittext layouts:
android:focusableInTouchMode="false"
Without this line, the EditText will react to touch-mode, and only listen to your onClick() the second time you click your EditText bar.
This will disable touch-mode for EditText, and fire onClick() in first time
focusableInTouchMode
Note: boolean that controls whether a view can take focus while in touch mode. If this is true for a view, that view can gain focus when clicked on, and can keep focus if another view is clicked on that doesn't have this attribute set to true.
than do as follows:
EditText1
EditText et_email = (EditText) findViewById(R.id.yourEditText1);
et_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do this
et_mobile.setText("");
//or this
et_mobile.getText().clear();
}
});
EditText2
EditText et_mobile = (EditText) findViewById(R.id.yourEditText2);
et_mobile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do this
et_email.setText("");
//or this
et_email.getText().clear();
}
});
This should help u out.
you are clearing the first one one touching the first one, change your variable names in first listener like this
if (!(et_email.getText().toString().equalsIgnoreCase("") && et_mobile.getText().toString().equalsIgnoreCase(""))) {
if (MotionEvent.ACTION_UP == event.getAction()) {
et_mobile.setText("");
et_email.setFocusableInTouchMode(true);
et_email.setFocusable(true);
et_email.requestFocus();
}
return true; // return is important...
} else
I hope this code helps you (it works for me)
edit1 = (EditText) findViewById(R.id.edit1);
edit2 = (EditText) findViewById(R.id.edit2);
edit1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
edit2.setText("");
}
});
edit2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
edit1.setText("");
}
});

onKey event for editText not firing

I'm having a really hard time getting the OnKey event to trigger on my EditText view. I've been Googling for over an hour now and it seems everyone says all you have to do is add a OnKeyListener to the view but it's not triggering it. I tried adding it to the entire Activity and also tried adding it to the view itself but neither way is triggering the function.
My code:
XML:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/interests_editText" />
Java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_post);
interests_editText = (EditText) findViewById(R.id.interests_editText);
interests_editText.setOnKeyListener(new OnKeyListener(){
public boolean onKey( View view, int keyCode, KeyEvent event){
Log.i("DEBUG","TeST");
if (keyCode == KeyEvent.KEYCODE_ENTER) {
return true;
}
else {
return false;
}
}
}
);
Update:
My final goal is to get it to recognize when you press space while in that editText view. I added to the XML
android:inputType="text"
and then changed the code to
public boolean onKey( View view, int keyCode, KeyEvent event){
Log.i("DEBUG","Outside");
if (keyCode == KeyEvent.KEYCODE_SPACE) {
Log.i("DEBUG","Space");
return true;
}
else {
return false;
}
Now the keyboard shows a Next button that when pressed logs "Outside" but it doesn't log "Space"
Do you wanna capture Enter event? If so, try setOnEditorActionListener
For your Update Info: capture space key, try addTextChangedListener
Following up on #BNK's answer I got it to work using the following code:
interests_editText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
String str = s.toString();
if(str.substring(str.length()-1, str.length()).equals(" "))
Log.i("DEBUG","Space pressed");
else if(str.substring(str.length()-1, str.length()).equals("\n"))
Log.i("DEBUG", "Enter pressed");
else
Log.i("DEBUG", "Pressed : " +str.substring(str.length()-1, str.length()) );
}}

pressKey() action will on invoke TextView.OnEditorActionListener

Given I have a Activity with such kind of setup:
EditText edtDeviceName;
#Override
public void onResume() {
super.onResume();
edtDeviceName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE || event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
// Do something.
}
}
}
}
And I want to test this using Espresso:
onView(withId(R.id.edtDeviceName)).perform(replaceText("DeviceName"));
onView(withId(R.id.edtDeviceName)).perform(pressKey(new EspressoKey.Builder().withKeyCode(KeyEvent.KEYCODE_ENTER).build()));
Then TextView.OnEditorActionListener method onEditorAction will not be called.
Is there any special call to make when using Espresso?
This will only work if the View is actually focussed, like this:
onView(withId(R.id.edtDeviceName)).perform(click());
After that, calls to pressKey will end up at the view and cause the action to be triggered.

setOnKeyListener not responding

I am new to Android and working through a to do list example from a book. I have one Activity which is displaying an EditText and a ListView beneath it. There is an onKey event which should add the text from the EditText to the ListView and clear the EditText. However, when I hit Enter on the keyboard all that happens is a new line is added to the EditText and nothing is added to the ListView.
The onCreate code is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do_list);
// Get UI references
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
myEditText.setText("test");
// Create ArrayList to store To Do items
final ArrayList<String> toDoItems = new ArrayList<String>();
// Create ArrayAdapter to bind items to List View
final ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
toDoItems);
// Bind Adapter to List View
myListView.setAdapter(aa);
myEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
(keyCode == KeyEvent.KEYCODE_ENTER)) {
toDoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
}
I've added the myEditText.setText("test"); just to ensure the reference to myEditText is working, which it is. I've tried removing the if statements from the onKey event and it just doesn't appear to be registering key events at all. Can anyone advise what I'm doing wrong here?
You could try using a OnEditorActionListener instead:
http://developer.android.com/reference/android/widget/TextView.html#setOnEditorActionListener(android.widget.TextView.OnEditorActionListener)
You could set on the edittext in XML:
android:imeOptions="actionDone"
and then in code:
myEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// your action here
return true;
}
return false;
}
)};
Are you using the virtual keyboard?
In that case the problem is that an OnKeyListener only gets called by hardware buttons. Take a look here:
http://developer.android.com/reference/android/view/View.OnKeyListener.html
The first line says: Interface definition for a callback to be invoked when a hardware key event is dispatched to this view.
Perpaps something line this will solve your problem: Validating edittext in Android
I was able to get that same example to work by adding the following attribute to the EditText element android:inputType="text". This changed the software keyboard that came up for the user and included a Send button.
In the setOnKeyListener code, I changed it to the following:
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP)
if (keyCode == KeyEvent.KEYCODE_ENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
Don't use KEYCODE_DPAD_CENTER as that's a hardware button for devices that had up, down, left, right arrows.
Following code solved such problem:
You just need to need to add addTextChangedListener like this.Rest is self- explanatory
editabltText.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)
{
}
});
Instead of setOnKeyListener, try to implement setOnEditorActionListener. Hope this helps.
<EditText
android:id="#+id/search"
android:singleLine="true"
android:imeOptions="actionSearch">
try to add singleLine and imeOption attributes.

Categories

Resources