【发布时间】:2016-05-02 21:54:56
【问题描述】:
我的应用有两个fragments,一个是列表,一个是详细视图,它们都以横向模式显示,只有列表以纵向显示。在配置更改时,如果我在两个fragments 的onCreateOptionsMenu 中放置一个断点,它们将被击中两次并且Actionbar 中的菜单项被复制。
我尝试在不同的事件中设置invalidateOptionsMenu,例如onResume 和onActivityCreated,但这似乎没有帮助。我不确定是什么导致onCreateOptionsMenu 被击中两次。
我注意到有一个解决方案 here,但这对我不起作用。它会在Activity 上的onStart 中导致java.lang.IllegalArgumentException No view found for for fragment。
更新
我在肖像模式下使用ViewPager 加载fragments:
public class Main extends SherlockFragmentActivity
{
private static List<Fragment> fragments;
@Override
public void onCreate(final Bundle icicle)
{
setContentView(R.layout.main);
}
@Override
public void onResume()
{
mViewPager = (ViewPager)findViewById(R.id.viewpager);
if (mViewPager != null)
{
fragments = new ArrayList<Fragment>();
fragments.add(new MyListFragment());
fragments.add(MyDetailFragment.newInstance(0));
fragments.add(MyDetailFragment.newInstance(1));
fragments.add(MyDetailFragment.newInstance(2));
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
}
}
private static class MyFragmentPagerAdapter extends FragmentStatePagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int index) {
return fragments.get(index);
}
@Override
public int getCount() {
return 4;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
在横向模式下,我正在通过 XML 添加fragments。这是layout-land 文件夹中的 main.xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:weightSum="3"
>
<fragment android:name="com.app.ListingFragment"
android:id="@+id/fragmentDetails"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="fill_parent"
/>
<fragment android:name="com.app.DetailFragment"
android:id="@+id/fragmentDetails"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="fill_parent"
/>
</LinearLayout>
这是layout 文件夹中的 XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_height="match_parent"
android:layout_width="match_parent"
/>
</RelativeLayout>
【问题讨论】:
-
请发布您的片段的解码代码。您是否在每个片段中添加不同的操作?是每个片段被调用两次(总共 4 次)还是每个片段只被调用一次?
-
我会仔细检查您在布局中添加片段的部分。确保您的片段没有添加两次。
-
@RobertEstivill @rciovati 抱歉,我在添加
fragments的位置添加了代码。在横向模式下,我通过 XML 添加它们,在纵向模式下,我通过ViewPager添加它们。我知道ViewPager下一个fragment已加载,出于性能考虑,这会导致问题吗?每个fragment都被调用两次,一次用于列表,一次用于详细信息,即使在景观中也是如此。
标签: android android-fragments android-actionbar actionbarsherlock