簡體   English   中英

Android 添加片段容器視圖后膨脹布局崩潰

[英]Android inflate layout crashes after adding fragment container view

目前我有一個擴展 AppCompatActivity 的自定義抽屜活動,如下所示:

public class DrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
    
    ...

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

        ...
    }


    @Override
    public void setContentView(int layoutResID) {
        frameLayout = findViewById(R.id.drawer_frame);
        LayoutInflater.from(getApplicationContext()).inflate(layoutResID, frameLayout);
        super.setContentView(drawerLayout);
    }

    ...
}

正如您在此處看到的,我覆蓋了 setContentView 方法,因此擴展此抽屜活動的活動的布局 ID 將傳遞到此方法並在抽屜活動的子視圖中膨脹。 簡而言之,我希望擴展此抽屜活動的所有活動都將具有導航抽屜。 它適用於一般活動。

但是現在,我有一個包含片段容器視圖並擴展抽屜活動的活動。 當我啟動此活動時,應用程序崩潰並出現以下錯誤:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.aaa, PID: 10730
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aaa/com.example.aaa.gym.GymActivity}: android.view.InflateException: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Error inflating class androidx.fragment.app.FragmentContainerView
        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 #29 in com.example.aaa:layout/activity_gym: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Error inflating class androidx.fragment.app.FragmentContainerView
     Caused by: android.view.InflateException: Binary XML file line #29 in com.example.aaa:layout/activity_gym: Error inflating class androidx.fragment.app.FragmentContainerView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:858)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1010)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:965)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1127)
        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 com.example.aaa.DrawerActivity.setContentView(DrawerActivity.java:57)
        at com.example.aaa.gym.GymActivity.onCreate(GymActivity.java:62)
        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)
     Caused by: java.lang.UnsupportedOperationException: FragmentContainerView must be within a FragmentActivity to use android:name="com.example.aaa.gym.PlaceFragment"
E/AndroidRuntime:     at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.java:142)
        at androidx.fragment.app.FragmentContainerView.<init>(FragmentContainerView.java:120)
            ... 28 more

正如您在此處所見,根本原因是java.lang.UnsupportedOperationException: FragmentContainerView must be within a FragmentActivity to use android:name="com.example.aaa.gym.PlaceFragment" 但是,活動應該能夠擴展片段,因為它擴展了 DrawerActivity,DrawerActivity 擴展了 AppCompatActivity,AppCompatActivity 擴展了 Fragment Activity。 我對此很困惑。

這是活動代碼:

public class GymActivity extends DrawerActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {

    private ActivityGymBinding binding;
    
    ...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        markers = new ArrayList<>();

        binding = ActivityGymBinding.inflate(getLayoutInflater());

        // here crashes, the actual crash line is the second line of the drawer activity's setContentView
        setContentView(binding.getRoot().getSourceLayoutResId()); 

        ...

    }
    
    ...
}

這是活動 xml

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/mapLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".gym.GymActivity">


    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:contentDescription="@string/title_activity_gym"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/place_fragment"
        android:name="com.example.aaa.gym.PlaceFragment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout="@layout/place_fragment" />

</androidx.constraintlayout.widget.ConstraintLayout>

而片段,幾乎沒有任何改變

public class PlaceFragment extends Fragment {

    private PlaceViewModel mViewModel;
    private PlaceFragmentBinding binding;

    public static PlaceFragment newInstance() {
        return new PlaceFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        mViewModel = new ViewModelProvider(requireActivity()).get(PlaceViewModel.class);

        mViewModel.getName().observe(getViewLifecycleOwner(), s -> binding.name.setText(s));
        mViewModel.getLocation().observe(getViewLifecycleOwner(), s -> binding.location.setText(s));

        return inflater.inflate(R.layout.place_fragment, container, false);
    }
}

fragment.xml,只是一個簡單的框架布局

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".gym.PlaceFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/name"
        android:text="Hello" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/location"
        android:text="Hello" />

</FrameLayout>

誰能看出我的應用程序崩潰的原因? 任何建議將不勝感激。

問題在這里:

LayoutInflater.from(getApplicationContext()).inflate(layoutResID, frameLayout);

您正在使用應用程序上下文 - 特別不是您的 Activity,因此不使用 Activity 的主題,您的 Application class 也不擴展FragmentActivity 您需要使用LayoutInflater.from(this)實際使用您的 Activity 作為布局充氣器。

然而,雖然這會修復您的崩潰,但您的GymActivity仍然無法工作,因為這些行:

binding = ActivityGymBinding.inflate(getLayoutInflater());

// here crashes, the actual crash line is the second line of the drawer activity's setContentView
setContentView(binding.getRoot().getSourceLayoutResId()); 

在這里,您創建了一個binding object,但從未真正將其添加到您的 Activity 中。 相反,您調用您的setContentView覆蓋,它會膨脹該視圖的全新實例。 這意味着對binding的任何更改都不會反映在您的 UI 中。

相反,您希望提供對setContentView的覆蓋,它接受一個View並調用 FrameLayout 上的addView以將已經膨脹的 View 添加到您的布局中。

@Override
public void setContentView(View view) {
    frameLayout = findViewById(R.id.drawer_frame);
    frameLayout.addView(view)
    // Note you should never be calling super.setContentView here.
    // You've already called it in your own onCreate()
}

這讓你可以像這樣使用它:

binding = ActivityGymBinding.inflate(getLayoutInflater());

setContentView(binding.getRoot()); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM