Leem
Leem

Reputation: 18308

Get the instance of Activity from the Child Fragment

My activity extends AppCompatActivity, and I started a Fragment there with support library fragment manager:

    public MyActivity extends AppCompatActivity {
        ...

        @Override
        public void onResume() {
          super.onResume();
          // show my fragment
   getSupportFragmentManager().beginTransaction().add(android.R.id.content, myFragment, TAG).commit();
        }
    }

My question is, in MyFragment, how can I get the instance of MyActivity who started it?

//NOTE: it extends android.support.v4.app.Fragment
public class MyFragment extends Fragment {
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // How to get the instance of MyActivity here?
        // I tried: getActivity() but it returns FragmentActivity 
       //& MyActivity is AppCompatActivity
    }
}

I know there is getActivity() function in Fragment, but it returns FragmentActivity: enter image description here

Upvotes: 1

Views: 1265

Answers (1)

Quick learner
Quick learner

Reputation: 11457

Try this

((MyActivity) getActivity()).

then access anything from activity class

Upvotes: 1

Related Questions