How to get the Activity in nested fragments?

时间:2015-07-08 15:45:05

标签: android android-fragments fragmentstatepageradapter

I'm trying to get the activity calling getActivity() in the fragments contained in a ViewPager and this ViewPager is contained inside a Fragment. I need to call some methods from this activity in those fragments but the getActivity is always returning NULL for this fragments.

I don't know if this is a good approach but I need the fragments contained by the view pager to update their contents based on action bar actions and display messages saying is done or there was an error.

Help with this would be greatly appreciated.

Here is the code:

Internal Fragment:

    public class ReportSessionsFragment extends ReportPageFragment implements IUpdateView {

    private static final String TAG = ReportSessionsFragment.class.getSimpleName();

    private Sessions fSessions;

    private List<Report> reportList = null;
    private ReportsAdapter adapter = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        settings = ((BaseActivity)getActivity()).settings;
    }

    @Override
    public void onStart() {
        super.onStart();
        setCounter(db.getSessionsCount());

        if(settings.getSelectedRoom() != null){
            reportList = db.getSessionsByRoom(settings.getSelectedRoom().getName(),
                    settings.getStatusSelectedList());
            adapter = new ReportsAdapter(getActivity(), reportList, EReport.Sessions);
            mRecyclerView.setAdapter(adapter);
        }

    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void reload() {
        HashMap<String, Object> parameters = new HashMap<>();
        parameters.put(Fetcher.REQUEST_PARAMETERS, getEventInformation());

        showProgress(getString(R.string.txt_requesting_sessions));
        fSessions = new Sessions(getActivity(), this);
        fSessions.handleSession(parameters, false);
    }

    @Override
    public void delta() {

    }

    @Override
    public void updateProcess(String message) {

    }

    @Override
    public void onProcessEnded(RequestType type, boolean isProvisioningCompleted, String message) {
        reportList = db.getSessionsByRoom(settings.getSelectedRoom().getName(),
                settings.getStatusSelectedList());
        adapter.notifyDataSetChanged();
        hideProgress();
    }

    @Override
    public void onError(Exception e, boolean isProvisioningCompleted) {
        hideProgress();
        showError(getString(R.string.txt_error_title),
                e.getMessage());
    }
}

Fragment containing the ViewPager:

    public class ReportSessionsFragment extends ReportPageFragment implements IUpdateView {

    private static final String TAG = ReportSessionsFragment.class.getSimpleName();

    private Sessions fSessions;

    private List<Report> reportList = null;
    private ReportsAdapter adapter = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        settings = ((BaseActivity)getActivity()).settings;
    }

    @Override
    public void onStart() {
        super.onStart();
        setCounter(db.getSessionsCount());

        if(settings.getSelectedRoom() != null){
            reportList = db.getSessionsByRoom(settings.getSelectedRoom().getName(),
                    settings.getStatusSelectedList());
            adapter = new ReportsAdapter(getActivity(), reportList, EReport.Sessions);
            mRecyclerView.setAdapter(adapter);
        }

    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void reload() {
        HashMap<String, Object> parameters = new HashMap<>();
        parameters.put(Fetcher.REQUEST_PARAMETERS, getEventInformation());

        showProgress(getString(R.string.txt_requesting_sessions));
        fSessions = new Sessions(getActivity(), this);
        fSessions.handleSession(parameters, false);
    }

    @Override
    public void delta() {

    }

    @Override
    public void updateProcess(String message) {

    }

    @Override
    public void onProcessEnded(RequestType type, boolean isProvisioningCompleted, String message) {
        reportList = db.getSessionsByRoom(settings.getSelectedRoom().getName(),
                settings.getStatusSelectedList());
        adapter.notifyDataSetChanged();
        hideProgress();
    }

    @Override
    public void onError(Exception e, boolean isProvisioningCompleted) {
        hideProgress();
        showError(getString(R.string.txt_error_title),
                e.getMessage());
    }
}

The Activity:

    public class ReportsActivity extends BaseActivity implements IReports {

    private static final String TAG = ReportsActivity.class.getSimpleName();

    private ReportsFragment reportFragment;
    private HashMap<Integer, MenuItem> menuReports;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        reportFragment = new ReportsFragment();
        addFragment(reportFragment);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_reports, menu);

        menuReports = new HashMap<>();

        for(int index = 0; index < menu.size(); index++ ){
            MenuItem mi = menu.getItem(index);
            menuReports.put(mi.getItemId(), mi);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        ReportPageFragment reportPage = (ReportPageFragment)reportFragment.getCurrentReportPage();

        switch (item.getItemId()){
            case R.id.action_reload:
                reportPage.reload();
                break;
            case R.id.action_delta:
                reportPage.delta();
                break;
        }

        return true;
    }

    @Override
    public void displayOptionsByReport(int position) {
        MenuItem miReload = null;
        if(menuReports != null){
             miReload = (MenuItem) menuReports.get(R.id.action_reload);
        }

        switch (position){
            case REPORT_SESSION:
                miReload.setVisible(true);
                break;
            case REPORT_ENROLLMENT:
                miReload.setVisible(true);
                break;
            case REPORT_REGISTRANTS:
                miReload.setVisible(false);
                break;
            case REPORT_ASSOCIATIONS:
                miReload.setVisible(false);
                break;
        }
    }
}

FragmentPagerAdapter:

public class ReportsPagerAdapter extends FragmentStatePagerAdapter {

private Context ctx;

public ReportsPagerAdapter(Context ctx, FragmentManager fm) {
    super(fm);
    this.ctx = ctx;
}

@Override
public Fragment getItem(int position) {
    Fragment fragment = null;

    switch (position){
        case 0:
            fragment = Fragment.instantiate(ctx, ReportSessionsFragment.class.getName());
            break;
        case 1:
            fragment = Fragment.instantiate(ctx, ReportEnrollmentFragment.class.getName());
            break;
        case 2:
            fragment = Fragment.instantiate(ctx, ReportRegistrantsFragment.class.getName());
            break;
        case 3:
            fragment = Fragment.instantiate(ctx, ReportAssociationsFragment.class.getName());
            break;
    }

    return fragment;
}

@Override
public int getCount() {
    String[] reportListNames = ctx.getResources().getStringArray(R.array.reports);
    return reportListNames.length;
}

@Override
public CharSequence getPageTitle(int position) {
    String[] reportListNames = ctx.getResources().getStringArray(R.array.reports);
    return reportListNames[position];
}
}

1 个答案:

答案 0 :(得分:7)

每个片段,即使是那些是另一个片段的孩子的片段,当它们被添加到片段树中时,会收到对onAttach()的调用。包含片段的活动作为参数传入。最简单的解决方案可能是将活动保存为片段的成员。然后在以后需要时可以使用。

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    //save the activity to a member of this fragment
    mHostActivity = activity;
}

对于始终位于树中固定深度的片段,另一种方法是根据需要多次使用getParent()来获取最顶层的片段。例如,在您的片段中,它们是寻呼机片段的子节点:

getParentFragment().getActivity()