我发现很多帖子解释了如何从Fragment
savedInstanceState
获取Bundle
但是,因为Activity
可以在4 Fragments
之间切换,我需要一个在方向开始变化时,在旋转之前知道哪个片段还活着的方法。
我有几个片段的原因是因为我使用的是导航抽屉,所以每个菜单项都是片段。
答案 0 :(得分:4)
我遇到了同样的问题,我修复了它,将其添加到导航抽屉活动代码中:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null){
//Handle the initial fragment transaction
}
...
}
例如,我有一个导航抽屉,带有" Home","设置"和"关于"作为菜单项,每个都有一个片段" home_fragment"," settings_fragment"和" about_fragment"。
如果我想" home_fragment"当导航抽屉活动启动时出现,我在OnCreate函数上使用此代码:
FragmentManager fM = getSupportFragmentManager();
fM.beginTransaction().replace(R.id.NavDrawContent,new home_fragment()).commit();
但我希望它只在(savedInstanceState == null)时执行,这样当我们在settings_fragment(例如)中更改手机方向时,它不会使home_fragment膨胀。
所以最后的代码(在导航抽屉活动OnCreate中):
super.onCreate(savedInstanceState);
if(savedInstanceState==null){
FragmentManager fM = getSupportFragmentManager();
fM.beginTransaction().replace(R.id.NavDrawContent,new home_fragment()).commit();
}
答案 1 :(得分:3)
在活动中,您将片段的实例保存在onSaveInstanceState()
中,然后在onCreate()
中恢复。
@Override
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
fragment = getSupportFragmentManager().getFragment(savedInstanceState, "KEY");
changeFragment(fragment, "MY TAG")
} else {
setupFragment();
}
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Fragment fragment = getSupportFragmentManager().findFragmentByTag("MY TAG");
if (fragment != null) {
getSupportFragmentManager().putFragment(outState, "KEY", fragment);
}
}
如果您需要知道保存了哪个片段,可以查看instanceof
,例如:
if (fragment instanceof SettingsFragment) {
// ...
}
答案 2 :(得分:0)
找到我自己的答案,毕竟这是一件非常简单的事情。我把解决方案留给了那些对我不熟悉的人,比如我。
<?php
if ( have_posts() ): //Checks if posts available
while( have_posts() ): the_post(); //loop starts
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<p><?php the_content(); ?></p>
<small>This entry was posted on: <?php the_date('l, jS F Y'); ?> at <?php the_time('g:i a'); ?> and is filed under <?php the_category(); ?></small>
<small>This Article was written by: <?php the_author_link(); ?></small>
<div class="post"><?php edit_post_link('Edit','','<strong>|</strong>'); //[8]?>
<?php comments_popup_link('Be the first to comment »', 'Just the one comment so far »', '% Comments »', '', 'Comments are Closed for this article.');?></div>
<?php
endwhile; //loop end
?>
<div class="navigation">
<div class="alignleft"><?php previous_posts_link('« Read Previous Blog Posts') ?></div>
<div class="alignright"><?php next_posts_link('Read More Blog Posts »','') ?></div>
</div> <?php endif; ?>