Fragment的一个简单例子
整体步骤如下:
- 新建一个CFragment的布局文件layout_cfragment.xml
- 新建一个DFragment的布局文件layout_dfragment.xml
- 新建一个CFragment类继承Fragment
- 新建一个DFragment类继承Fragment
- 将布局分别加载到这两个类中
- 在Activity中添加Fragment并显示
如何实现以上的操作,这里我给出了代码,因为内容很简单,一看就能明白。
layout_cfragment.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:gravity="center"
android:background="#00ff00"
android:orientation="vertical">
<TextView
android:id="@+id/cfragment_tv"
android:layout_width="wrap_content"
android:textSize="30sp"
android:text="我是CFragment"
android:textColor="#ff0000"
android:textAllCaps="false"
android:layout_height="wrap_content" />
</LinearLayout>
这里就是一个线性布局和一个TextView。
layout_dfragment.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:gravity="center"
android:background="#09F7F7"
android:orientation="vertical">
<TextView
android:id="@+id/dfragment_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是DFragment"
android:textAllCaps="false"
android:textColor="#ff0000"
android:textSize="30sp" />
</LinearLayout>
这里也是一个线性布局和一个TextView。
CFragment类中的代码如下:
public class CFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// 加载布局文件
View view = inflater.inflate(R.layout.layout_cfragment, container, false);
return view;
}
}
此处可以看到,我重写了onCreateView()方法,并在里面加载了上面刚刚写的那个布局文件。
DFragment类中的代码如下:
public class DFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.layout_dfragment, container, false);
return view;
}
}
此处与上面一样,所以没什么可讲的。
Activity部分
java代码部分:
public class FragmentDemoActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_demo);
}
}
这里就是创建activity时的一个默认代码。
布局文件部分:
<?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">
<fragment
android:id="@+id/cfragment"
android:name="com.example.lenovo.review.Fragment_Test.CFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<fragment
android:id="@+id/dfragment"
android:name="com.example.lenovo.review.Fragment_Test.DFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
以上我们使用了标签在布局中添加碎片,注意为每个标签设置id值和name属性,name是要添加的Fragment所在的位置。