简体   繁体   中英

Android: Call fragment functions from Activity, the fragment function contains getActivity() and returns null

I have a fragment as follows:

public class F1 extends Fragment {

    ...
    public void function1 (){
        activity = getActivity();
    }

}

When trying to call this function in the activity which has this fragment,

public class Activity1 extends Activity {

    private F1 f1 = new F1();
    f1.function1();

}

it returns null .

How can I solve this problem? Can anyone provide a working code example?

It returns null because the fragment didn't attach to the Activity. so use Fragment Manager to access Fragments and also you can use Activity Context in onAttach(Activity activity) , and it would be for sure not Null.

@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity);
    this.activityContext = activity; //then use activity context
}

and for getting your Fragment Instance :

F1 f1 = (F1) getFragmentManager().findFragmentByTag(F1.TAG_FRAGMENT);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM