Android EditText long onKeyListener press

1.1k views Asked by At

I have a non touch android system, with physical keyboard buttons. I want to detect long key presses in EditText.

I tried using the onKeyDown (start tracking) and onKeyLongPress in MainActivity, but it doesnt work, because the focus is with EditText.

P.S : I am using this EditText in a fragment and not MainActivity

2

There are 2 answers

1
josedlujan On

Try this.

editText.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        Log.i("KEY", Integer.toString(keyCode));
        return false;
    } });
0
blueaac On

Since I wanted to use this in a fragment and not the MainActivity I dint have the liberty of using the onKeyDown and onKeyLongPress from MainActivity, the only solution I found was extending EditText in a custom class and overriding the OnKeyUp and OnKeyLongPress method and use that in the Fragment i want

public class CustomEditText extends EditText {

    public CustomEditText(Context context) {
        super(context);
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode >= 7 && keyCode <= 16) {                                
                event.startTracking();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {

        if(keyCode >= 7 && keyCode <= 16) {
                Log.v("Testing", "Long Key Press");
                return true;
        }
        return super.onKeyLongPress(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }
}

and then we need to use this Custom EditText text box in place of regular EditText in XML

<com.project.example.util.CustomEditText
    android:id="@+id/et"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"        
</com.project.example.util.CustomEditText>