按照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方法。

相关内容

热门资讯

推荐攻略!cloudpoker... 这是一款非常优秀的cloudpoker怎么开挂 ia辅助检测软件,能够让你了解到cloudpoker...
玩家必知教程!wepoker辅... 玩家必知教程!wepoker辅助插件功能,hhpoker到底可以作弊码,详细教程(有挂攻略)是由北京...
来一盘!红龙poker辅助工具... 来一盘!红龙poker辅助工具,wepoker有透视吗,玩家教程(有挂教程),支持语音通讯、好友开房...
热点推荐!wepoker轻量版... 1、热点推荐!wepoker轻量版辅助,悦扑克脚本,2025版教程(有挂软件)。2、wepoker轻...
推荐几款新版!wepoker游... 1、推荐几款新版!wepoker游戏的安装教程,德普之星有透视辅助吗,揭秘教程(有挂透明)。2、德普...
玩家攻略推荐!wepoker俱... 玩家攻略推荐!wepoker俱乐部辅助,wepoker怎么获得好牌,2025新版技巧(有挂透明);小...
发现一款!wepoker透视有... 发现一款!wepoker透视有没有,hhpoker可以控制牌吗,实用技巧(有挂教程);玩家必备必赢加...
教程辅助!wpk辅助软件,hh... 教程辅助!wpk辅助软件,hhpoker有没有辅助,细节方法(有挂透明);大神普及一款德州ai内幕,...
必看攻略!wepoker有透视... 必看攻略!wepoker有透视吗,德州透视竞技联盟,攻略教程(有挂辅助);大神普及一款德州ai内幕,...
今日焦点!wepoker好友房... 今日焦点!wepoker好友房开挂,hhpoker到底可以作弊码,透明挂教程(有挂软件)关于hhpo...