Fragment全家桶

Fragment又称碎片,从Android 3.0引入,能够兼顾手机和平板的尺寸。

1.基础使用

创建一个自定义Fragment类,使其继承自Fragment。

public class FragmentDemo extends Fragment {
         @Override
         public View onCreatView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
   //通过inflate方法把Fragment布局动态加载进来
   View view=inflater.inflate(R.layout.FragmentDemo,container,false);
   return view;
    }


}

在Activity_main.xml中使用<fragment>标签在布局中添加碎片,特别注意需要通过android:name属性来显式指明要添加的碎片类名,必须将类的包名也加上。

android:name="com.example.fragmenttest.FragmentDemo"

2.动态添加碎片

1.创建待添加的碎片实例。

2.获取FragmentManager,在活动中可以直接通过调用getSupportFragment()方法得到。

3.开启一个事务,通过调用beginTransaction()方法开启

4.向容器中添加碎片,用add()方法,替换碎片,用replace()方法实现,需要传入容器的id和待添加的碎片实例。

5.提交事务,调用commit()方法来完成。

6.补充:调用FragmentTransaction提供的addToBackStack()方法,可以用于将一个事务添加到返回栈中,参数接收一个名字用于描述返回栈的状态,一般传入null。

Transaction transaction=getSupportFragmentManager().beginTransaction();
//初始添加Fragment
transaction.add(int containerViewId, Fragment fragment);
//替换Fragment
transaction.replace(int containerViewId, Fragment fragment);
//在碎片中模拟返回栈
transaction.addToBackStack(null);
transaction.commit();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值