《第一行代码》第一版 158页到160页
写在前面的话:一定要给fragment标签加id号,不然实际运行时会一闪而过。
第一步:新建一个工程(略),参见以前的文章
第二步:新建一个LeftFragment 后,把它java文件中其它自动产生的代码都清除,只留下onCreateView()函数。不清除最后生成APP后会闪退。
public class LeftFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_left, container, false);
}
}
第三步:新建一个RightFragment后,把它java文件中其它自动产生的代码都清除,只留下onCreateView()函数。不清除最后生成APP后会闪退。
public class RightFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_right, container, false);
}
}
第四步:修改fragment_left.xml中的代码为如下代码,它原来是constraint布局,现在要改为线性布局, 修改原因是constraint布局很难做。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
tools:context=".LeftFragment">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Button" />
</LinearLayout>
第五步:修改fragment_right.xml中的代码为如下代码,它原来是constraint布局,现在要改为线性布局, 修改原因是constraint布局很难做。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:background="#00ff00"
tools:context=".RightFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textSize="20sp"
android:text="This is right fragment"
/>
</LinearLayout>
第六步: 修改主界面的布局为线性布局,代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity"
>
<fragment
android:id="@+id/left_fragment"
android:name="com.jintingbo.myapplication16.LeftFragment"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="match_parent"
tools:layout="@layout/fragment_left" />
<fragment
android:id="@+id/right_fragment"
android:name="com.jintingbo.myapplication16.RightFragment"
android:layout_width="0dp"
android:layout_weight="0.5"
android:layout_height="match_parent"
tools:layout="@layout/fragment_right" />
</LinearLayout>