Sunday, October 9, 2016

[Android][Resolved] onfocuschange called multiple times

Problem

Set an onFocusChange event to EditText, and when user click one of the EditText, multiple times of onFocusChange event are fired.

Source

This is the code in an Activity,  which implements View.OnFocusChangeListener :
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int itemId = v.getId();
        String clickedETName = null;
        if(v instanceof EditText){
            EditText clickedEditText = (EditText) v;
            clickedETName = clickedEditText.getTag().toString();
            mFirebaseAnalytics.setUserId("1");
            mFirebaseAnalytics.setUserProperty("EditText", clickedETName);
        }
        Toast.makeText(FormActivity.this, "You have focused on " + clickedETName, Toast.LENGTH_LONG).show();
        Bundle bundle = new Bundle();
        bundle.putString(FirebaseAnalytics.Param.ITEM_ID, String.valueOf(itemId));
        bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "EditText");
        bundle.putString(FirebaseAnalytics.Param.VALUE, clickedETName);
        mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
    }

Solves

Add a if statement ( (text in yellow) ) to check hasFocus is true (it mean the new focus state of view) before you log the code.

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        int itemId = v.getId();
        String clickedETName = null;
        if(v instanceof EditText){
            EditText clickedEditText = (EditText) v;
            clickedETName = clickedEditText.getTag().toString();
            mFirebaseAnalytics.setUserId("1");
            mFirebaseAnalytics.setUserProperty("EditText", clickedETName);
        }
        if(hasFocus) {
            Toast.makeText(FormActivity.this, "You have focused on " + clickedETName, Toast.LENGTH_LONG).show();
            Bundle bundle = new Bundle();
            bundle.putString(FirebaseAnalytics.Param.ITEM_ID, String.valueOf(itemId));
            bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "EditText");
            bundle.putString(FirebaseAnalytics.Param.VALUE, clickedETName);
            mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
        }
    }

 Reference

http://stackoverflow.com/questions/17341946/how-can-i-detect-focused-edittext-in-android
http://stackoverflow.com/questions/23761658/android-onfocuschange-is-fired-multiple-times

1 comment :