Call parent's activity from a fragment

2019-02-05 15:06发布

If I'm inside a Fragment how can I call a parent's activity?

3条回答
闹够了就滚
2楼-- · 2019-02-05 15:55

Yes, Its right by calling getActivity and cast it with parent activity to access its methods or variables ((ParentActivityName)getActivity())

Try this one.

ParentActivityName is parent class name

查看更多
走好不送
3楼-- · 2019-02-05 15:58

The most proper way is to make your Activity implement an Interface and use listeners. That way the Fragment isn't tied to any specific Activity keeping it reusable. Into the Fragment:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

That way, you make the Activity listen to the fragment when it's attached to it.

See also:

查看更多
beautiful°
4楼-- · 2019-02-05 15:59

Simply call your parent activity using getActivity() method.

CardView cardView = (CardView) getActivity().findView(R.id.your_view);
查看更多
登录 后发表回答