从片段中调用父级的活动

use*_*708 30 android fragment android-activity

如果我在片段中,我怎样才能调用父母的活动?

Dco*_*hef 67

是的,它通过调用getActivity并使用父活动强制转换来访问其方法或变量 ((ParentActivityName)getActivity())

试试这个吧.

ParentActivityName 是父类名


Xtr*_*ica 14

最合适的方法是使您的Activity工具成为一个Interface并使用侦听器.这样Fragment就没有任何特定的Activity保持可重用性.进入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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,Activity当它附加到片段时,你就可以监听它.

也可以看看: