fragment也是可以在我们的布局文件中直接使用的
<?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=".home.activity.MainActivity">
<fragment
android:id="@+id/fragmentTest"
android:name="com.home.fragment.Test"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
那么在activity中拿到该fragment呢?
FragmentManager fragmentManager = getSupportFragmentManager();
TestFragment testFragment = (TestFragment) fragmentManager.findFragmentById(R.id.fragmentTest);
注意:无论我们是否需要在activity中使用该fragment,我们都必须给该fragment声明id属性或者声明一个tag属性,否则会报异常,如下:
使用tag属性
<?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="vertical"
tools:context=".home.activity.MainActivity">
<fragment
android:tag="fragmentTest"
android:name="com.bawie.bawaymall160a.home.fragment.CatagoryFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
//代码中使用
FragmentManager fragmentManager = getSupportFragmentManager();
TestFragment testFragment = (TestFragment) fragmentManager.findFragmentByTag("testFragment);
注意这里使用findFragmentByTag()方法
异常信息如下:
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #45: Must specify unique android:id, android:tag, or have a parent with an id for com.bawie.bawaymall160a.home.fragment.CatagoryFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3717)
at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:405)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:387)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.bawie.bawaymall160a.home.activity.MainActivity.onCreate(MainActivity.java:23)