java - fragment 替换错误

标签 java android android-intent android-fragments android-activity

我正在尝试替换我的一个 fragment ,但由于这些错误我无法这样做。但是我已经有了这些导入,因此我不知道这里出了什么问题。

错误1

Error:(73, 96) error: incompatible types
required: android.support.v4.app.FragmentTransaction
found:    android.app.FragmentTransaction

错误2

Error:(72, 48) error: incompatible types
required: Fragment
found:    FragmentMap

导入

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

fragment 替换代码

Fragment newFragment = new FragmentMap();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

transaction.replace(R.id.detail_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();

enter image description here

最新截图 enter image description here

最佳答案

对于错误1

Error:(73, 96) error: incompatible types
required: android.support.v4.app.FragmentTransaction
found:    android.app.FragmentTransaction

getFragmentManager() 更改为 getSupportFragmentManager() 它应该可以工作。

getSupportFragmentManager() is used when you are using support lib (your case). and getFragmentManager() is used when not using support lib.

对于错误2

Error:(72, 48) error: incompatible types
required: Fragment
found:    FragmentMap

因此要替换 fragment ,请使用以下命令:

Fragment newFragment = new FragmentMap();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.detail_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();

newFragment 是要替换的 fragment ,但会引发错误。

Make sure the FragmentMap or any other fragment to be replaced, is extended by Fragment class (of support lib and not the normal one, because newFragment is an object of Fragment from support lib) using import android.support.v4.app.Fragment; and not import android.app.Fragment;

关于java - fragment 替换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30414749/

相关文章:

java - Struts 2 - 通过迭代动态填充 optgroup

java - 如何在Java类中封装一个startActivityForResult并在调用该方法的Activity上获取onActivityResult

Android - 检查应用程序的证书

android - 如何为 Activity 的半透明背景添加圆角?

新的一天或重大时间变化的 Android Intent

java - 无法单击位于不同框架中的单选按钮

java - 如何在应用程序部署后立即打开所有连接?

android - CameraSourcePreview 未填满整个屏幕高度

java - 将第二个 Activity 的值(value)保存到第一个 Activity ,而不会丢失更新的数据

Android App Play 商店重定向