Home » Android » What does getActivity() mean?

What does getActivity() mean?

Posted by: admin February 23, 2018 Leave a comment

Questions:

What does getActivity() mean? I saw in somewhere, they wrote MainActivity.this.startActionMode(mActionModeCallback) instead of getActivity(). could someone explain what this two lines mean?

  someView.setOnLongClickListener(new View.OnLongClickListener() {
        // Called when the user long-clicks on someView
        public boolean onLongClick(View view) {
            if (mActionMode != null) {
                return false;
            }

            // Start the CAB using the ActionMode.Callback defined above
            mActionMode = getActivity().startActionMode(mActionModeCallback);
            view.setSelected(true);
            return true;
        }
    });
Answers:

Two likely definitions:

Questions:
Answers:

getActivity() is used for fragment. For activity, wherever you can use this, you can replace the this in fragment in similar cases with getActivity().

Questions:
Answers:

getActivity()- Return the Activity this fragment is currently associated with.

Questions:
Answers:

I to had a similar doubt what I got to know was getActivity() returns the Activity to which the fragment is associated.

The getActivity() method is used generally in static fragment as the associated activity will not be static and non static member cannot be used in static member.

I used <code>getActivity()</code> here to get non-static activity to which the the placeholder fragment is associated.