Android之Fragment的使用(一)

本文介绍了Android中的Fragment,包括创建Fragment、静态与动态添加、Fragment间通信以及数据传递的多种方式。通过示例展示了如何在Activity中管理和操作Fragment,以及如何在Fragment与Activity之间进行双向通信。
摘要由CSDN通过智能技术生成

每个人都会累,没人能为你承担所有悲伤,人总有一段时间要学会自己长


本讲内容:Fragment的使用

Fragment是一种可以嵌入在活动当中的UI片段,它能让程序更加合理和充分地利用大屏幕的空间,因而在平板上应用的非常广泛。


一、创建一个Fragment

继承Fragment类,重写生命周期方法,需要重写一个onCreateView()方法来返回这个Fragment的布局。


示例一:在一个活动当中添加两个碎片,并让这两个碎片平分活动空间(静态加载)


下面是res/layout/left_fragment.xml 布局文件:

<?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:orientation="vertical" >

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Button" />

</LinearLayout>

下面是res/layout/right_fragment.xml 布局文件:

<?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="#0f0"
    android:orientation="vertical" >

     <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="This is right fragment"
        android:textSize="20sp" />

</LinearLayout>


下面是LeftFragment.java文件:

public class LeftFragment extends Fragment {

	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		// 通过LayoutInflater的inflate()方法将定义的布局动态加载进来并转换成View对象
		/**
		 * resource:Fragment需要加载的布局文件
		 * root:加载布局文件的父ViewGroup
		 * attactToRoot:false为不返回父ViewGroup
		 */
		View view = inflater.inflate(R.layout.left_fragment, container, false);
		return view;
	}
}

下面是Right Fragment .java文件:

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;
	}
}

下面是res/layout/activity_main.xml 布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  • 9
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值