Fragment为碎片,相当于小的Activity,作用很是重要。可分为静态Fragment和动态Fragment,现在就来简单介绍一下静态Fragment。
一.创建第一个Fragment布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFC200"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第一个Fragment" android:id="@+id/btn_fragment_one" android:layout_gravity="center_horizontal" /> </LinearLayout>
二.编写第一个Fragment代码
public class FragmentOne extends Fragment { private Button btn; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment_one,container,false); Toast.makeText(getContext(),"第一个碎片",Toast.LENGTH_LONG).show(); return view; } }三.创建第二个Fragment布局<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#46EB1C"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="第二个Fragment" android:id="@+id/btn_fragment_two" android:layout_gravity="center_horizontal" /> </LinearLayout>四.编写第二个Fragment代码public class FragmentTwo extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.fragment_two,container,false); return view; } }五.设置主布局,把两个Fragment都添加到主布局中
<?xml version="1.0" encoding="utf-8"?> <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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.zhiyuan3g.myfragment.MainActivity"> <fragment android:id="@+id/fragment_one" android:name="com.zhiyuan3g.myfragment.fragment.FragmentOne" android:layout_width="200dp" android:layout_height="match_parent" tools:layout="@layout/fragment_one"></fragment> <fragment android:id="@+id/fragment_two" android:name="com.zhiyuan3g.myfragment.fragment.FragmentTwo" android:layout_width="200dp" android:layout_alignParentRight="true" android:layout_height="match_parent" tools:layout="@layout/fragment_two"></fragment> </RelativeLayout>六.运行并查看结果