Android Fragment 片段 的简单使用

Fragment时寄生在Activity里的,所以,Activity的生命周期会影响到Fragment的生命周期。Fragment有两种创建方式,分别是动态创建更静态创建,不管如果,我们都要先创建Fragment子类

1.创建Fragment子类
首先新建个布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_light"
    android:orientation="vertical" >


</LinearLayout>

然后新建个类继承Fragment,重写onCreateView方法,在方法里用打气筒将刚才那个布局打成View并且返回。

package com.hyw.test;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TestFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_test, container, false);
    }

}

2.让Fragment寄生到Activity里

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <fragment 
        android:id="@+id/fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.hyw.test.TestFragment"/>

</RelativeLayout>

注意: 中的 android:name 属性指定要在布局中实例化的 Fragment 类。

然后,你还可以动态地把Fragment塞到Activity里,先获取FragmentManager

FragmentManager fragmentManager = getFragmentManager();

然后通过FragmentManager 开启一个事务

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

别忘了动态new一个Fragment

TestFragment fragment = new TestFragment();

最后通过FragmentTransaction把Fragment塞到你想塞到的地方并提交,那个地方需是ViewGroup,下面那个id就是那地方的id

fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

不过,在您调用 commit() 之前,您可能想调用 addToBackStack(),以将事务添加到片段事务返回栈

fragmentTransaction.addToBackStack(null);

3.那么Activity跟Fragment怎么互相交流呢?

Fragment可以通过getActivity获取Activity然后执行Activity里的方法

View listView = getActivity().findViewById(R.id.list);

同样地,您的 Activity 也可以使用 findFragmentById() 或 findFragmentByTag(),通过从 FragmentManager 获取对 Fragment 的引用来调用片段中的方法。

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值