为什么我得到错误膨胀类片段?

时间:2016-09-02 17:08:43

标签: android android-fragments

我有一个包含片段的活动。

活动外观:

activity_main.xml中:

    <?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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="keepInTouch.mainScreen.MainActivity">



    <TextView
        android:id="@+id/textV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <fragment
        android:id="@+id/fragmnet_main_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout="@layout/fragment_main_list" />
</LinearLayout>


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);    
    }

片段看: fragment_main_list.xml

<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="keepInTouch.today.MainListFragment">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/mainFragmentListTitle"
        android:background="#e43d3d"
        android:textColor="#371b1b" />


    <ListView
        android:id="@+id/lvKits"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


public class MainListFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main_list, container, false);
    }

我收到以下错误: android.view.InflateException:二进制XML文件行#41:错误膨胀类Fragment

我试着替换 MainActivity扩展了AppCompatActivity 有: MainActivity扩展了FragmentActivity

但我得到了同样的结果。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您忘记了android:name中的fragment属性。这样做:

<fragment 
        android:id="@+id/fragmnet_main_list" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        android:name="keepInTouch.today.MainListFragment"
        tools:layout="@layout/fragment_main_list" />