Android – onAttach(Context) not called for API 23

Overview

In Android, Fragment is very common class when coding. This class is very important on every project. From Api 23, Android SDK had an important change at Fragment class. This is:

onAttach(Activity) => onAttach(Context).

Developers need to keep code run on two versions of Fragment. I will write my solution for this issue.

How to implement

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.onAttach();
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            this.onAttach();
        }
    }

    private void onAttach() {
        // Enter your code here.
    }

In summary

With my solution, your code will run on all version of Android SDK.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s