[英]Fragment detach() and attach() doesn't update view
I have a navigation drawer in my Application and want to change the TextView
in the Menu from Login (when no user is logged in) to My Account (when a user logs in). 我的应用程序中有一个导航抽屉,并且想要将菜单中的
TextView
从“登录”(当没有用户登录时)更改为“我的帐户”(当用户登录时)。 I use attach()
and detach()
methods to reload the fragment. 我使用
attach()
和detach()
方法重新加载片段。 However, the view doesn't seem to get updated. 但是,该视图似乎没有更新。 Using logs, I have verified that the piece of code executes correctly.
使用日志,我已经验证了这段代码可以正确执行。
Here is the onClick
action that happens when I click logout, which seems to successfully logout my user. 这是当我单击注销时发生的
onClick
动作,这似乎成功注销了我的用户。 SharedPrefs
is a class used to manage SharedPreferences
. SharedPrefs
是用于管理SharedPreferences
的类。 The deletePrefs()
method works good, because if I press logout and restart the application, the user is successfully logged out. deletePrefs()
方法效果很好,因为如果我按注销并重新启动应用程序,则用户将成功注销。
case 2:
SharedPrefs.deletePrefs(getContext());
closeDrawer();
NavigationDrawerFragment mNavigationDrawerFragment = MainActivity.getNavigationDrawerFragment();
mNavigationDrawerFragment.setUserData("", "", BitmapFactory.decodeResource(getResources(), R.drawable.avatar));
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commit();
Log.d("Fragment", "detach, attach");
break;
Here is the method that builds the Menu. 这是构建菜单的方法。 It is called in the
onCreateView()
method of my Fragment. 在我的Fragment的
onCreateView()
方法中调用它。
public List<NavigationItem> getMenu() {
items = new ArrayList<NavigationItem>();
items.add(new NavigationItem("Home", getResources().getDrawable(R.drawable.ic_home)));
if (!SharedPrefs.isLogin(getContext()))
items.add(new NavigationItem("Login", getResources().getDrawable(R.drawable.ic_login)));
else
items.add(new NavigationItem("My Account", getResources().getDrawable(R.drawable.ic_my_account)));
items.add(new NavigationItem("Logout", getResources().getDrawable(R.drawable.ic_logout)));
return items;
}
When detaching and attaching, isn't onCreateView()
executed again? 分离和附加时,是否不会再次执行
onCreateView()
? Thus the Menu should get rebuilt and the TextView
should change, right? 因此,应该重建菜单,并更改
TextView
,对吗?
EDIT: So using logs, I see that the onCreateView()
method is not called again when detaching and reattaching. 编辑:因此使用日志,我看到分离和重新附加时,不会再次调用
onCreateView()
方法。 Is this normal? 这正常吗? Or am I detaching and reattaching the wrong way?
还是我以错误的方式分离并重新连接?
I also faced the same problem while using fragment update. 使用片段更新时,我也遇到了同样的问题。 I fixed it like this:
我这样修复:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(this).attach(this).commitAllowingStateLoss();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.