I have the following problem: When I resume activity after have called another activity, the system create automatically another fragment so when I update the view from other method, they update the hidden fragment. How can I avoid this?
@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;
...
}
Thanks!
You need to check if the layout already has fragment added in that ID
FragmentManager manager = getSupportFragmentManager();
if (manager.findFragmentById(R.id.container) == null) {
manager.beginTransaction().add(R.id.container, fragment)
.commit();
}
Also if you want to change fragment to different one you may want to check also the fragment that is already added in it.
Then it would look something like this
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) {}
}
Notify that add has changed to replace in this case.