Home > Software design >  How to get Call back when we enter keyBoard enterbutton in android
How to get Call back when we enter keyBoard enterbutton in android

Time:03-08

This is my Edit text:

<EditText
            android:id="@ id/name_ed"
            style="@style/enter_kid_details_style"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="4dp"
            android:background="@drawable/edittext_background"
            android:fontFamily="@font/inter_semibold"
            android:hint="@string/name"
            android:maxLines="1"
            android:imeOptions="actionNext"
            android:inputType="text"
            android:textColor="@color/black"
            android:textSize="@dimen/tfl_16sp" />

This is my code which i am trying to click even when press enter button of keyboard

edName.setOnKeyListener(View.OnKeyListener { _, keyCode, _ ->
        if (keyCode == KeyEvent.KEYCODE_ENTER ) {
            //Perform Code
                Toast.makeText(this,"Clicked",Toast.LENGTH_LONG).show()
            return@OnKeyListener true
        }
        false
    })

I dont know what i am doing mistake but i am unable to get call back when i.e unable to show toast when we click on keyboard enter button please help me in this suggest me what i am doing wrong .

CodePudding user response:

STEP 1- In your xml, add the imeOptions attribute to the editText

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

STEP 2- Then, in your Java code, add the OnEditorActionListener to the same 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;
        }
    });

OR

mAddItemEditText.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;
        }
    });
  • Related