繁体   English   中英

屏幕方向发生变化时,Android片段彼此重叠显示

[英]Android Fragments Displaying On Top Of Each Other When Screen Orientation Changes

我有一个导航菜单,向用户显示各种操作模式。 当用户选择特定选项时,活动是加载相应的片段(例如:Add Product应当加载AddProduct片段)。

加载工作正常-我将FragmentManager与FragmentTransaction一起使用,以新片段替换当前片段。 当屏幕旋转时出现问题-我使用的当前两个片段彼此重叠显示。

这是我为NavigationDrawerListener(执行加载的部分)设置的代码:

  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    DrawerLayout drawerLayout = (DrawerLayout) currentActivty.findViewById(R.id
            .homeDrawer);
    TextView heading = (TextView) currentActivty.findViewById(R.id.AppHeadingTextView);
    switch (position)
    {
        case 0:
            heading.setText("Home");
            drawerLayout.closeDrawers();
            UserMainScreenFragment homeScreen = new UserMainScreenFragment();
            FragmentManager homeManager = currentActivty.getFragmentManager();
            FragmentTransaction homeTransaction = homeManager.beginTransaction();
            homeTransaction.replace(R.id.contentArea, homeScreen);
            homeTransaction.commit();
            break;
        case 2:
            heading.setText("Add a Product");
            drawerLayout.closeDrawers();
            AddProductFragment newProductFragment = new AddProductFragment();
            FragmentManager manager = currentActivty.getFragmentManager();
            FragmentTransaction replace = manager.beginTransaction();
            replace.replace(R.id.contentArea, newProductFragment);
            replace.commit();
           break;
    }
}

您需要根据方向为所需的活动创建单独的布局。

您必须为两个方向添加不同的布局(具有相同的名称),然后Android会根据方向自动为相应的xml填充。

文件结构如下所示,

res
 - drawable
 - layout                        // for portrait
    - layout_name.xml            
 - layout-land                   // for landscape
    - layout_name.xml            // same name should be used
 - .....

在此处找到示例解决方案

在您的活动中,您需要检查savedInstanceState是否为null以避免再次添加相同的片段:

//when the orientation changes, the savedInstanceState bundle is not null
if(savedInstanceState!=null){
//add your fragment to the layout
}

另一件事,我注意到您通过currentActivty.getFragmentManager()引用了片段管理器;

也许currentActivty.getFragmentManager(); 对被破坏的活动有较旧的引用,如果使用的是支持库,也应该使用getSupportFragmentManager()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM