android-fragments 为什么在使用FragmentContainerView时会出现android.view.InflateException异常

bxpogfeg  于 2022-11-13  发布在  Android
关注(0)|答案(2)|浏览(174)

我对碎片还很陌生,我肯定我没有正确地理解事情。但我希望我现在能从中学到东西。
我按照下面的指南将我的xml与片段连接起来:https://developer.android.com/guide/fragments/create .但是当启动应用程序时,我得到一个错误,说有些部分不兼容。
以下是我的文件:
main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView
    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"
    tools:context=".MainActivity"
    android:id="@+id/main"
    android:orientation="horizontal"
    >
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="30dp">

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="@string/brand"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/item"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        android:textStyle="bold"
        />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        app:srcCompat="@drawable/gibson_1"
        />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/price"
            android:gravity="right"
            />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            android:gravity="right"
            >
            <EditText
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:inputType="phone"
                android:layout_marginRight="15dp"
                />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Add to cart"
                android:drawableLeft="@drawable/drawablestart"
                android:id="@+id/addCart"
                />
        </LinearLayout>


    </FrameLayout>

</androidx.fragment.app.FragmentContainerView>

MainActive.java

package at.hlpinkafeld.android.musicstore;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    public MainActivity() {
        super(R.layout.activity_main);
    }

    @Nullable

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .setReorderingAllowed(true)
                    .add(R.id.main, ProductDetailFragment.class, null)
                    .commit();
        }

    }
}

fragment.java

package at.hlpinkafeld.android.musicstore;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.android.material.textview.MaterialTextView;

public class ProductDetailFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.activity_main,container,false);
        System.out.println(view);
        return view;
    }
}

该误差

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: at.hlpinkafeld.android.musicstore, PID: 13020
    java.lang.RuntimeException: Unable to start activity ComponentInfo{at.hlpinkafeld.android.musicstore/at.hlpinkafeld.android.musicstore.MainActivity}: android.view.InflateException: Binary XML file line #11 in at.hlpinkafeld.android.musicstore:layout/activity_main: Views added to a FragmentContainerView must be associated with a Fragment. View android.widget.FrameLayout{58ede95 V.E...... ......I. 0,0-0,0} is not associated with a Fragment.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3635)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
     Caused by: android.view.InflateException: Binary XML file line #11 in at.hlpinkafeld.android.musicstore:layout/activity_main: Views added to a FragmentContainerView must be associated with a Fragment. View android.widget.FrameLayout{58ede95 V.E...... ......I. 0,0-0,0} is not associated with a Fragment.
     Caused by: java.lang.IllegalStateException: Views added to a FragmentContainerView must be associated with a Fragment. View android.widget.FrameLayout{58ede95 V.E...... ......I. 0,0-0,0} is not associated with a Fragment.
        at androidx.fragment.app.FragmentContainerView.addView(FragmentContainerView.kt:266)
        at android.view.ViewGroup.addView(ViewGroup.java:5048)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1131)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1088)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:686)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:538)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:485)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:710)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:195)
        at androidx.activity.ComponentActivity.onCreate(ComponentActivity.java:356)
        at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:217)
        at at.hlpinkafeld.android.musicstore.MainActivity.onCreate(MainActivity.java:25)
        at android.app.Activity.performCreate(Activity.java:8051)
        at android.app.Activity.performCreate(Activity.java:8031)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3608)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3792)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2210)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:201)
        at android.os.Looper.loop(Looper.java:288)
        at android.app.ActivityThread.main(ActivityThread.java:7839)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

寻求帮助和解释为什么它不像那样工作,会很好

xnifntxz

xnifntxz1#

我想您可能希望尝试将一个简单的片段加载到Activity中。
试试这个代码。它对你很有效。
如需更多信息:click

**注意:**总是创建一个这样的新对象来加载片段new ProductDetailFragment(),并在onCreate()中使用setContentView();
**1.**首先,创建一个完美的Activity来加载片段。

MainActivity.class

public class MainActivity extends AppCompatActivity {

String TAG = "MainActivity";

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

    getSupportFragmentManager().beginTransaction()
                .setReorderingAllowed(true)
                .add(R.id.main, new ProductDetailFragment(), null)
                .commit();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   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"
    tools:context=".MainActivity"
    android:id="@+id/main"
    android:orientation="horizontal"
    >
</RelativeLayout>

**2.**创建片段ProductDetailFragment.class

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ProductDetailFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.fragment_product_details,container,false);
        System.out.println(view);
        return view;
    }
}

**3.**对片段fragment_product_details.xml进行不同布局

<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/brand" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/item"
        android:textAppearance="@style/TextAppearance.AppCompat.Headline"
        android:textStyle="bold" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        app:srcCompat="@drawable/gibson_1" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:text="@string/price" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="right"
        android:orientation="horizontal">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="15dp"
            android:inputType="phone" />

        <Button
            android:id="@+id/addCart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/drawablestart"
            android:text="Add to cart" />
    </LinearLayout>
</FrameLayout>
nle07wnf

nle07wnf2#

您误解了链接中的实际代码:-https://developer.android.com/guide/fragments/create
您将片段xml代码放在片段容器视图中,该视图位于主Activity中。
您只需要声明下面定义的片段容器视图。
fragment container视图是主容器,它包含主Activity中的如下片段。

<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="<provide your fragment class here from your code it is ProductDetailFragment>" />

然后在布局目录中创建名为fragment_product_detail的片段xml文件:-
然后把你的xml代码片段放进去。如下所示。
产品详细信息. xml:-

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp">

<TextView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:text="@string/brand"
    />
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/item"
    android:textAppearance="@style/TextAppearance.AppCompat.Headline"
    android:textStyle="bold"
    />

<ImageView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    app:srcCompat="@drawable/gibson_1"
    />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/price"
        android:gravity="right"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:gravity="right"
        >
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="phone"
            android:layout_marginRight="15dp"
            />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Add to cart"
            android:drawableLeft="@drawable/drawablestart"
            android:id="@+id/addCart"
            />
    </LinearLayout>


</FrameLayout>

然后在您的fragmentonCreateView方法中,确保膨胀片段布局,如下所示:-

View view =inflater.inflate(R.layout.fragment_product_detail,container,false);

这将解决您的问题。如果您仍面临任何问题,请告诉我。

相关问题