IllegalStateException替换活动中的片段时,找不到Fragment的视图

时间:2019-06-05 06:22:35

标签: java android fragment containers illegalstateexception

我正在尝试一个活动,其中两个片段接连显示。下面是我的活动和片段代码。

MainActivity

public class DeliveryActivity extends BaseActivity {

private static final String ROOT_FRAG = "root_fragment";

@Override
protected int layoutRes() {
    return R.layout.activity_delivery;
}

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

    if (savedInstanceState == null)

    getSupportFragmentManager()
    .beginTransaction().add(R.id.fl_container,
                new DeliveryListFragment())
    .addToBackStack(ROOT_FRAG).commit();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

public void navigateToDetailsScreen() {
             getSupportFragmentManager()
             .beginTransaction()
             .replace(R.id.fl_container,
             new DeliveryDetailFragment()).commit();
}

}

BaseActivity.java

public abstract class BaseActivity extends DaggerAppCompatActivity {

@LayoutRes
protected abstract int layoutRes();

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layoutRes());
}

}

activity_delivery.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fl_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />

虽然我要添加第一个片段,但容器很好并且可以添加,但是当我尝试替换片段(第二个片段)时,它给了我下面的错误。

java.lang.IllegalArgumentException: No view found for id 0x7f08004c (com.assessment.project:id/fl_container) for fragment SecondFragment{15674f3 #2 id=0x7f08004c}

1 个答案:

答案 0 :(得分:0)

我认为您的功能应该是这样的

public void navigateToDetailsScreen(View view) {
             getSupportFragmentManager()
             .beginTransaction()
             .replace(R.id.fl_container,
             new DeliveryDetailFragment()).commit();
}