我尝试动态添加片段,但是每次我切换到动态添加片段而不是静态添加片段时,应用程序都会停止运行。
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);
}
}
答案 0 :(得分:0)
关键是inflate
方法中的第三个布尔参数。它将放大的视图附加到父视图。要解决错误,您应该将onCreateView
方法更改为此:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment, container, false);
}
避免将null作为父级传递,以正确设置LayoutParams。