加载背景片段并在两个活动之间共享

时间:2016-02-04 02:00:15

标签: android android-fragments android-activity

片段是否仅存在于创建它们的活动中?我想要做的是我有一个splashactivity.java和mainactivity.java和一个BackgroundDataFragment.java我在splashactivity中创建BackgroundDataFragment然后转移到mainactivity但是无法在那里找到加载的BackgroundDataFragment。电话

mBackgroundFragment = (BackgroundDataFragment) getSupportFragmentManager()
                .findFragmentByTag(FragmentTags.FRAGMENT_DATA_TAG.name());

总是在mainactivity.java中将BackgroundDataFragment返回为null。我

public class BaseActivity extends AppCompatActivity
{
    /**
     * The data fragment.
     */
    protected BackgroundDataFragment mBackgroundFragment;
}

splashactivity.java

public class SplashActivity extends BaseActivity {

    private BroadcastReceiver mAppStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String status = intent.getStringExtra(BundleTags.APP_DATA_STATUS.name());
            if (StringUtils.isNotEmpty(status) && "loading".equals(status)) {
             showProgressDialog(getString(R.string.loading_progress_app), getSupportFragmentManager());
            } else {
                dismissProgressDialog(getSupportFragmentManager());
                loadDataAndStartMainActivity();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        if (mBackgroundFragment == null) {
            mBackgroundFragment = (BackgroundDataFragment) getSupportFragmentManager()
                    .findFragmentByTag(FragmentTags.FRAGMENT_DATA_TAG.name());
            if (mBackgroundFragment == null) {
                DialogHelper.showProgressDialog(getString(R.string.loading_progress_app), getSupportFragmentManager());
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                mBackgroundFragment = new BackgroundDataFragment();
                transaction.add(mBackgroundFragment, FragmentTags.FRAGMENT_DATA_TAG.name());
                transaction.commit();
            }
        }
    }

    private void loadDataAndStartMainActivity() {
        Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        startActivity(intent);
        // close this activity
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(mAppStatusBroadcastReceiver,
                new IntentFilter(PreferencesKey.APP_DATA_STATUS));
    }

    @Override
    protected void onPause() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mAppStatusBroadcastReceiver);
        super.onPause();
    }
}

mainactivity.java

public class MainActivity extends BaseActivity  {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (mBackgroundFragment == null) {

        // This call always return BackgroundDataFragment as null
        mBackgroundFragment = (BackgroundDataFragment) getSupportFragmentManager()
                .findFragmentByTag(FragmentTags.FRAGMENT_DATA_TAG.name());

        if (mBackgroundFragment != null) {
            //setup view for the page etc
        }
    } else {
        //setup view for the page etc
    }
  }
}

3 个答案:

答案 0 :(得分:1)

您无法在两个活动之间共享片段,因为每个活动都有自己的FragmentManager。要在两个活动之间共享数据,您可以使用Bundle,或在Application对象中存储数据。

答案 1 :(得分:1)

你不能在两个活动之间分享片段。 findFragmentByTag将尝试通过其标记查找片段(如果它在xml中)或通过事务添加到活动中。还有一点需要注意的是,你已经调用了finish(),因此活动将被破坏,片段的生命周期取决于活动,因此它也会被破坏。

您可以加载数据并放入包中,然后通过意图传递它。

Intent intent = new Intent(SplashActivity.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("key2",parcelableObject);
intent.putExtra("key1",bundle);
startActivity(intent);

答案 2 :(得分:0)

谢谢@Rey Pham和@Damanpreet Singh。是的,该片段属于活动的片段管理器,因此无法通过fragmentmanager共享。我找到的解决方法是保存片段的状态,然后在bundle中传递它,最终从另一个activity中的已保存状态重新创建它。我认为这对于昂贵的碎片非常有用。虽然我认为除非绝对必要,否则我们应该避免这样做。例如。我的目标是将应用程序数据加载到后台片段并显示启动画面,直到它加载然后移动到主活动,其他片段将使用它。我需要阅读更多关于DataLoaders等的内容,看看有没有更好的方法在片段之间共享app相关数据,而不使用非ui背景片段。

splashactivity.java

Intent intent = new Intent(SplashActivity.this, MainActivity.class);
        Fragment.SavedState savedState = getSupportFragmentManager().saveFragmentInstanceState(mBackgroundFragment);
        intent.putExtra(FragmentTags.FRAGMENT_DATA_TAG.name(), savedState);
        startActivity(intent);
        // close this splashactivity
        finish();

mainactivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

            mBackgroundFragment = new DataFragment();
            Fragment.SavedState backgroundFragmentState = getIntent().getParcelableExtra(FragmentTags.FRAGMENT_DATA_TAG.name());
            mBackgroundFragment.setInitialSavedState(backgroundFragmentState);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(mBackgroundFragment, FragmentTags.FRAGMENT_DATA_TAG.name());
            transaction.commit();
    }