碎片的简单使用
1.首先创建两个布局left_fragment.xml和right_fragment.xml,并分别添加以下代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#ff0000"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="这是第一个"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="这是第二个"/>
</LinearLayout>
2.分别创建对应的leftfragment和rightfragment的两个类,分别继承Fragment,并重写onCreateView方法,修改它的内容
public class leftFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_left,container,false);
return view;
}
}
public class rightFragment extends Fragment {
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_right,container,false);
return view;
}
}
3.接着修改mainActivity.xml文件里面的代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:name="com.example.demo_fragment.leftFragment"
android:id="@+id/left_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
<fragment
android:name="com.example.demo_fragment.rightFragment"
android:id="@+id/right_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"/>
</LinearLayout>
这里的name指向的是我们第二步的left fragment这个文件的路径,这里我的包名是com.example.demo_fragment,因为我实在这个包下创建的
接着运行看效果