按照Android开发者文档添加Fragment不起作用怎么办?
创始人
2024-08-23 10:00:16
0
  1. 确保Activity已经设置了布局,布局中必须要有fragment的容器。

例如,在activity_main.xml中可以添加一个FrameLayout来作为fragment的容器:


 
    
 

  1. 创建Fragment

例如,新建一个MyFragment类,继承自Fragment,并重写onCreateView方法:

public class MyFragment extends Fragment {
 
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_my, container, false);
        //初始化控件,设置事件监听等
        return rootView;
    }
}
  1. 在Activity中加载Fragment

例如,在MainActivity中加载MyFragment:

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        //加载MyFragment
        MyFragment fragment = new MyFragment();
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, fragment).commit();
    }
}
  1. 注意事项:
  • fragment的容器ID必须和beginTransaction().add()中的ID一致;
  • 加载fragment时,需要在Activity的onCreate方法中执行;
  • 当Activity被销毁时,FragmentManager会自动保存fragmentBackStack的状态,在Activity被恢复时,FragmentManager会自动恢复fragmentBackStack的状态。
  • 如果添加的fragment已经处于显示状态,那么使用add方法添加不起作用,需要使用replace方法。

相关内容

热门资讯

科技揭秘!智星菠萝辅助,hhp... 科技揭秘!智星菠萝辅助,hhpoker透视脚本下载,爆料教程(有挂教程)是一款可以让一直输的玩家,快...
揭秘!hhpoker视频巡查真... 您好,hhpoker视频巡查真的假的这款游戏可以开挂的,确实是有挂的,需要了解加微【13670430...
揭秘!hhpoker哪个俱乐部... 揭秘!hhpoker哪个俱乐部靠谱,来玩app 德州 辅助,细节揭秘(有挂辅助);支持多人共享记分板...
技术分享!wepoker安装教... 技术分享!wepoker安装教程,线上德州的辅助器是什么,扑克教程(有挂攻略);大神普及一款德州ai...
最新技巧!wepoker辅助器... 自定义wepoker买脚本靠谱吗系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅...
传递经验!wepoker手机插... 传递经验!wepoker手机插件,wepoker如何设置透视,辅助教程(有挂攻略),支持语音通讯、好...
1.9分钟了解!wepoker... 1.9分钟了解!wepoker分析,约局吧德州透视,必赢教程(有挂透明);实战中需综合运用上述技巧,...
揭秘几款!hhpoker软件可... 1、揭秘几款!hhpoker软件可以玩吗,哈糖大菠萝攻略,科技教程(有挂辅助)(UU poker、h...
玩家必看!wepoker轻量版... 您好,拱趴大菠萝自动计算机器人这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很...
玩家必备教程!wepoker辅... 玩家必备教程!wepoker辅助器怎么弄,aapoker怎么拿好牌,规律教程(有挂方法);wepok...