Android活动在恢复时自动创建新的片段实例

时间:2014-11-27 08:55:07

标签: android android-fragments refresh onresume

我有以下问题: 当我在调用另一个活动后恢复活动时,系统会自动创建另一个片段,因此当我从其他方法更新视图时,它们会更新隐藏的片段。 我怎么能避免这个?

    @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;

            ...
        }

谢谢!

1 个答案:

答案 0 :(得分:2)

您需要检查布局是否已在该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) {}
}

在这种情况下,通知添加已更改为替换