Search code examples
androidandroid-edittextfocuslistener

Android onFocusChange is fired multiple times


I'm using a List Adapter (extends SimpleCursorAdapter) to populate some data.

I'm calling View.SetOnFocusChangeListener in bindView where i attach the listener to the desired EditText. The problem is that the event is fired 4 times where in the end the EditText loses it's focus, until i click again where the event is fired 3 times and the EditText retains focus.

I think it should only be called once. Is the OnTouch event responsible for this?

Here is my code:

@Override
public void bindView(View view, Context context, Cursor cursor) {       
    view.setId(cursor.getPosition());//Setting the row id to the corresponding cursor row id for easier data manipulation
    super.bindView(view, context, cursor);
    EditText etItemQuantity = (EditText)view.findViewById(R.id.etItemQuantity);
    if(!isNumeric(etItemQuantity.getText().toString())) {
        etItemQuantity.setFocusable(false);
        etItemQuantity.setFocusableInTouchMode(false);
        etItemQuantity.setClickable(false);
    } else {
        etItemQuantity.setFocusable(true);
        etItemQuantity.setFocusableInTouchMode(true);
        etItemQuantity.setClickable(true);
        etItemQuantity.setOnFocusChangeListener(ofcl);
        etItemQuantity.setOnEditorActionListener(oeal);
    }

}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    View view = inflater.inflate(layout, null);
    return view;
}

View.OnFocusChangeListener ofcl = new View.OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!(v instanceof EditText)) {                     
            return;
        }
        EditText tableEt = (EditText)v;

        if(hasFocus) {
            tableEt.setTag(tableEt.getText().toString());
            tableEt.setText("");
        } else {
            if(tableEt.getText().toString().equals("")) {           
                tableEt.setText(tableEt.getTag().toString());
                tableEt.setTag(null);
            }
        }


    }
};

Solution

  • Adding the following line int my activity in the manifest fixed the problem:

            android:windowSoftInputMode="adjustPan"
    

    Not sure why though.