我有以下问题:当我在调用另一个活动之后恢复活动时,系统会自动创建另一个片段,因此当我从其他方法更新视图时,它们会更新隐藏的片段。如何避免这种情况?
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
frag_ID = R.layout.frag;
AccountFragment fragment = new AccountFragment();
getSupportFragmentManager().beginTransaction().add(R.id.container, fragment).commit();
}
@Override
protected void onStart()
{
super.onStart();
... update method ...
TextView textView = (TextView) findViewById(R.id.total_account_textview);
// when I launch another activity and the return to this, this textview is on a hidden fragment and not in the foreground fragment
}
public static class AccountFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(frag_ID, container, false);
}
@Override
public void onViewCreated (View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
TextView textView;
...
}
谢谢!
您需要检查布局是否已经在该ID中添加了片段
FragmentManager manager = getSupportFragmentManager();
if (manager.findFragmentById(R.id.container) == null) {
manager.beginTransaction().add(R.id.container, fragment)
.commit();
}
同样,如果您想将片段更改为另一个片段,则可能还要检查已经添加到其中的片段。
然后看起来像这样
private void setFragment(Class<? extends Fragment> fragmentClass) {
try {
Fragment newFragment = fragmentClass.newInstance();
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.container);
if (currentFragment == null || !currentFragment.getClass().equals(newFragment)) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment).commit();
}
} catch(Exception ignored) {}
}
在这种情况下,通知add已更改为替换。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句