Android——碎片用法

第一步:新建一个left_fragment布局

 第二步:新建一个right_fragment布局

 第三步:新建一个LeftFragment类,并继承自Fragment

public class LeftFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.left_fragment,container,false);
        return view;
    }
}

第四步:新建一个RightFragment类,并继承自Fragment

public class RightFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.right_fragment,container,false);
        return view;
    }
}

第五步:修改activity_main的代码

动态添加:

第一步:新建所需的另一个界面another_right_fragment(设置了一个文本) 

第二步:创建一个AnotherRightFragment类(加载创建的布局)

public class AnotherRightFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.another_right_fragment,container,false);
        return view;
    }

第三步:修改activity_main布局

 第四步:修改MainActivity中的内容

1、注册点击事件

2、replaceFragment方法() 

(1)创建待添加的实例

 (2)获取FragmentManager,在活动中直接调用getSupportFragmentManager()得到。

FragmentManager fragmentManager=getSupportFragmentManager();

(3)开启一个事务,通过beginTransaction()开启。

FragmentTransaction transaction = fragmentManager.beginTransaction();

(4)向容器内添加或替换碎片,使用replace()方法完成

transaction.replace(R.id.right_layout,fragment);

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

transaction.commit();

(2)(3)(4)(5)总体代码:

在碎片中返回模拟栈

 碎片与活动之间的通信

1、在活动中得到相应碎片

RightFragment rightFragment = getSupportFragmentManager().findFragmentById(R.id.right_fragment);

2、在碎片中得到活动

MainActivity activity = (MainActivity) getActivity();

碎片的状态

1、运行状态

2、暂停状态

3、停止状态

4、销毁状态

动态加载

一、使用限定符(自动判断使用双页/单页模式)

第一步:修改activity_main文件

 删除多余代码,只留下左侧碎片,并使其充满整个父布局

第二步:在res目录下新建layout-large文件夹,在其下面新建一个布局,叫做activity_main.xml

 二、使用最小宽度限定符

第一步:与上述一样

第二步:在res目录下新建layout-sw600dp文件夹,在其下面新建一个布局,叫做activity_main.xml

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值