Android Key Listener - android

Hello i have one key listener
email = (EditText)findViewById(R.id.email);
email.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(keyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
return true;
}else{
return false;
}
}
});
but when I press enter the event does not work, any idea?

Check the documentation for the OnKeyListener.
Interface definition for a callback to be invoked when a hardware key
event is dispatched to this view. The callback will be invoked before
the key event is given to the view. This is only useful for hardware
keyboards; a software input method has no obligation to trigger this
listener.
I'm guessing your are not using a hardware keyboard.

Yes i have one solution, im add a android:singleLine="true", regards!
<EditText
android:layout_width="fill_parent"
android:layout_height="52dp"
android:id="#+id/email"
android:background="#drawable/customs_borders"
android:textColor="#ffd3e8d6"
android:gravity="center"
android:textStyle="bold"
android:textSize="23dp"
android:hint="EMAIL"
android:singleLine="true"/>

Related

EditText OnKeyListener with setFocus not working as per expected

I am using an Android device with physical hardware keyboard.
I have two EditTexts (Part No and Qty) and Two Buttons (Reset and Save) on screen.
After user key in Qty, they want to press Enter key from physical keyboard to trigger "Save" function.
My current Save function will save the data to file and clear the data on screen and set the focus to Part No.
It seems like my onKeyListener didn't return True once it was consumed and it trigger another Enter key action to move my cursor to Qty field (by right, it should stay in Part No field).
I thought return True will indicate this Enter key has been consumed, am I understanding correct?
My two EditText are put directly under ConstraintLayout (not under any sub-layout).
Any idea on where my code goes wrong?
Below is my piece of code for layout.
<EditText
android:id="#+id/etPart"
android:layout_width="200dp"
android:maxLength="20"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:maxLines="1"
android:inputType="text"
android:imeOptions="actionNext"
app:layout_constraintLeft_toRightOf="#+id/tvPart"
app:layout_constraintTop_toTopOf="parent"/>
<EditText
android:id="#+id/etQty"
android:layout_width="100dp"
android:maxLength="5"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:inputType="number"
android:maxLines="1"
android:imeOptions="actionDone"
app:layout_constraintLeft_toRightOf="#+id/tvQty"
app:layout_constraintTop_toBottomOf="#id/etPart"
android:nextFocusDown="#id/etPart"/>
Below is my Java code.
This is in onCreate method.
etQty.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER){
saveData(null);
// I tried to use return true here, sames result, no different.
}
return false;
}
});
This is the functions.
public void saveData(View view) {
// check and save data to file logic.
// ...... etc.
mProductViewModel.insert(product);
resetView(null);
}
public void resetView(View view) {
etPart.setText(null);
etQty.setText(null);
// I am expecting the focus will stay in Part No box but it is not. It will jump to Qty field.
etPart.requestFocus();
}
After checking with the specialist, I came to understand that I also need to handle Action Up (Key Up) too.
Below is the working code.
etQty.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_UP){
saveData(null);
return true;
}
return false;
}
});
This is usually caused by soft keyboard, can you try this code?
etPart.requestFocus();
final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.restartInput(etPart);
imm.showSoftInput(etPart, 0);

onEditor action not working when trying to respond to the tick on the android numeric soft keyboard

I have an EditText in my app with an input type of number:
<EditText
android:id="#+id/answerText"
style="#style/GeneralTextStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/question"
android:layout_toRightOf="#id/equals"
android:inputType="number"
android:paddingTop="#dimen/activity_vertical_margin"
android:maxLength="3"
android:visibility="invisible"
tools:text="ans"/>
So when the EditText has focus the numeric keyboard is displayed. I am trying to repond to the user pressing the tick button after supplying a value in the EditText but I can't get it to work.
I've tried the following code which I've put inside the onCreate method but it isn't working:
answerGivenText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE){
return true;
}
return false;
}
});
Can anyone help please?
I think you should add the
android:imeOptions="actionDone"
attribute to your edittext.
That code is exactly what you need, but you are not doing anything inside it, you're just intercepting the click and returning true, indicating that you handled it to other listeners on the stack.
You would do whatever it is you want to do when the user clicks the tick in the
if (actionId == EditorInfo.IME_ACTION_DONE)
section. And turn on the DONE action in your layout. What exactly are you trying to achieve?

onKey not triggering when backspace keyboard button click android

I am using the OnKeyListener on a EditText on Android to identify when the backspace(delete) of the keyboard was pressed and handle myself the deletion of the character(doing this because it's a field that were synchronized with external service).
Some people said to use the TextWatcher and handle in one of the textchanged events. While this can be a viable solution. I still trying to do it with the onKey.
The problem is that the onKey is only triggered when there is not text(empty) in the EditText and pressed backspace. If there's text the onKey is not triggered until it deletes all text.
Anyone What I am missing for the onKey to be triggered in all the clicks in the backspace?
This is my xml:
<EditText
android:id="#+id/trackpad_speller_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="false"
android:layout_margin="10dp"
android:layout_weight="0.8"
android:focusable="true"
android:focusableInTouchMode="true"
android:imeOptions="actionDone" />
and I am setting the listener on the fragment
this.spellerInput.setOnKeyListener(this);
And my OnKey
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
if (presenter.getSpellerType() == SpellerType.FREE_SPELLER) {
Log.d(TAG, "backspace pressed and ignored for FREE_SPELLER");
return false;
} else {
Log.d(TAG, "backspace pressed for SEARCH_SPELLER");
presenter.deleteChar();
}
}
return true;
}
Any help would be appreciated! Thanks :D
I don't know if this is the best way, but I found that setting the setInputType of the EditText InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD solves the problem and makes the onKey be triggered in all backspace clicks.
spellerInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
Hope it helps

Android imeOptions="actionDone" not working

I am trying to get a login screen for an Android app and so far this is my code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical">
<EditText
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="text"
android:singleLine="true"
android:imeOptions="actionNext">
<requestFocus />
</EditText>
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true"
android:imeOptions="actionDone" />
<Button
android:id="#+id/buttonLaunchTriage"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="#string/login" />
</LinearLayout>
</RelativeLayout>
When I try to run it, the keyboard shows the right keys but when I try to press done after entering the password, nothing happens. I am using this to handle the button press:
private void setupLoginButton() {
Button launchButton = (Button) findViewById(R.id.buttonLaunchTriage);
launchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText username = (EditText) findViewById(R.id.patient_start_userName_value);
EditText password = (EditText) findViewById(R.id.patient_start_password_value);
try {
if(TriageApplicationMain.validateUser(username.getText().toString(),password.getText().toString(),getApplicationContext()))
{
Toast.makeText(StartActivity.this,
"Launching Triage Application", Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(StartActivity.this, MainActivity.class));
}
else
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
StartActivity.this);
// set dialog message
alertDialogBuilder
.setMessage("Incorrect Credentials")
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
I know this is a lot of code, but if anyone could help me here it would be great. This is for a school project.
PS: I have searched through Google for a solid hour before posting this so please don't criticize for not doing that. If you find a link that is useful then please share.
Just add android:inputType="..." to your EditText. It will work!! :)
You should set OnEditorActionListener for the EditText to implement the action you want to perform when user clicks the "Done" in keyboard.
Thus, you need to write some code like:
password.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Do whatever you want here
return true;
}
return false;
}
});
See the tutorial at android developer site
Qianqian is correct. Your code only listens for the button click event, not for the EditorAction event.
I want to add that some phone vendors may not properly implement the DONE action. I have tested this with a Lenovo A889 for example, and that phone never sends EditorInfo.IME_ACTION_DONEwhen you press done, it always sends EditorInfo.IME_ACTION_UNSPECIFIED so I actually end up with something like
myEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event)
{
boolean handled=false;
// Some phones disregard the IME setting option in the xml, instead
// they send IME_ACTION_UNSPECIFIED so we need to catch that
if(EditorInfo.IME_ACTION_DONE==actionId || EditorInfo.IME_ACTION_UNSPECIFIED==actionId)
{
// do things here
handled=true;
}
return handled;
}
});
Also note the "handled" flag (Qianqian didn't explain that part). It might be that other OnEditorActionListeners higher up are listening for events of a different type. If your method returns false, that means you didn't handle this event and it will be passed on to others. If you return true that means you handled/consumed it and it will not be passed on to others.
Use android:inputType="Yours" then
android:lines="1"
android:imeOptions="actionDone"
After trying many things, this is what worked for me:
android:maxLines="1"
android:inputType="text"
android:imeOptions="actionDone"
just Add this to your attributes :
android:inputType="textPassword"
Doc: here
You should set OnEditorActionListener for the EditText to implement the action you want to perform when user clicks the "Done" in keyboard.
Just to add to Qianqian & peedee answers:
Here's the reason why the action id is EditorInfo.IME_ACTION_UNSPECIFIED (0) for any enter event.
actionId
int: Identifier of the action. This will be either the identifier you supplied, or EditorInfo#IME_NULL if being called due to the enter key being pressed.
(Source: Android documentation)
So the proper way to handle enter key events would be:
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_NULL) {
// Handle return key here
return true;
}
return false;
}
in XML
android:id="#+id/edittext"
android:maxLines="1"
android:inputType="text"
android:imeOptions="actionDone"
in Java
edittext.setOnEditorActionListener((textView, actionId, keyEvent) - > {
if (actionId == EditorInfo.IME_ACTION_DONE) {
/////////////Your Code Here////////////////
return true;
}
return false;
});

Recommendations on the use of an EditText

I need a way to take text from a "EditText" as soon as the user presses "Enter" and it should also call a method if it loses focus.
I created EditText like this:
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/button2"
android:ems="10" >
To receive key presses your EditText needs to have focus:
editText1.setFocusableInTouchMode(true);
editText1.requestFocus();
then set the onkeylistener():
editText1.setonKeyListener(new OnKeyListener(
#override onKey(View v, int keyCode, KeyEvent event) {
if(event.getAction()==KeyEvent.ACTION_UP && keyCode==KeyEvent.KEYCODE_ENTER){
// what you need to do when Enter is pressed
return true;
}else return false;
}
For focus lost, you need to implement the View.onFocusChange interface and check that hasFocus is false
Use an EditText action listener. Refer to this question, it's probably the same: Handle Enter in EditText
For detecting loss in focus:
if(!(et.isFocused)){
//call your method here
}

Categories

Resources