gpt4 book ai didi

java - 如何从抽屉导航中重新加载/刷新 fragment

转载 作者:行者123 更新时间:2023-11-29 08:49:50 24 4
gpt4 key购买 nike

我有一个使用抽屉导航的 android 应用程序。我遵循了本教程 Naviation Drawer Tutorial

并且能够在我的 MainActivity.java

上使用它

我在 MainActivity 中有这段代码来设置我想显示的 fragment :

public void displayView(int position) throws Exception {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new DashboardFragment();
break;
case 1:
fragment = new EventsFragment();
break;
default:
break;
}

if (fragment != null) {
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, fragment);
fragmentTransaction.commit();

// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}

现在在我的 EventsFragment.java 中,我有这段代码来重新加载 fragment :

    @Override
public void onRefreshStarted(View view) {
MainActivity mainAct = new MainActivity();
try {
// reload and set the displayValue position to 1 = EventsFragment()
mainAct.displayView(1);
} catch (Exception e) {
e.printStackTrace();
}
}

我收到这个错误:

java.lang.IllegalStateException: Activity has been destroyed. 

我相信我在这部分代码中遇到了这个错误:fragmentTransaction.commit();

最佳答案

如果您想要引用父 Activity,请使用 Fragment.getActivity()

@Override
public void onRefreshStarted(View view) {
Activity mainAct = getActivity();

// Make sure the host Activity is infact an instance of MainActivity, and has displayView()
if(mainAct instanceof MainActivity) {
mainAct.displayView(1);
}
}

关于java - 如何从抽屉导航中重新加载/刷新 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23324709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com