gpt4 book ai didi

android - 无法动态添加 fragment

转载 作者:行者123 更新时间:2023-11-30 05:01:20 25 4
gpt4 key购买 nike

我曾尝试动态添加 fragment ,但每次我切换到动态添加 fragment 而不是静态添加 fragment 时,应用程序总是停止。

package com.hiro.empty;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity
{

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

Fragment fragment = new MyFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
}

Logcat 输出:

2019-10-02 15:38:51.056 16022-16022/com.hiro.empty E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hiro.empty, PID: 16022
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:5106)
at android.view.ViewGroup.addView(ViewGroup.java:4935)
at android.view.ViewGroup.addView(ViewGroup.java:4875)
at android.view.ViewGroup.addView(ViewGroup.java:4848)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:887)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
...

MyFragment 类

public class MyFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment, container);
}
}

最佳答案

关键是 inflate 方法中的第三个 bool 参数。它会将膨胀的 View 附加到父级。要修复错误,您应该将 onCreateView 方法更改为:

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

避免将 null 作为父级传递以正确设置 LayoutParams。

关于android - 无法动态添加 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58196422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com