1.静态加载
1、首先,新建FragmentTest.java
类继承fragment
public class FragmentTest extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
return view;
}
}
2、创建fragment中的布局fragment_test.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是fragment" />
</LinearLayout>
3、创建activity中的布局activity_main.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">
<fragment
android:id="@+id/fragment_test"
android:name="com.bignerdranch.android.litepalstudy.fragment.FragmentTest"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
注意,这里的fragment控件一定要加android:id="@+id/fragment_test"
不然会报异常
android.view.InflateException: Binary XML file line #13: Binary XML file line #13: Error inflating class fragment
4、创建MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
2.动态加载
动态加载fragment的静态加载fragment的一、二步相同。从第三步开始。
3、创建activity_main.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">
<FrameLayout
android:id="@+id/fragment_test"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Framelayout
是一个用来存放Fragment
的容器
3、创建MainActivity.java类
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建fragment管理类
FragmentManager fm = getSupportFragmentManager();
//查找当前容器中是否有fragment
Fragment fragment = fm.findFragmentById(R.id.fragment_test);
if (fragment == null){
//如果没有,创建fragment
fragment = new FragmentTest();
//添加fragment到activity中
fm.beginTransaction()
.add(R.id.fragment_test, fragment)
.commit();
}
}
}
网友评论