我正在使用 reference. 中的代码
当我在我的程序中输入该代码时,出现如下图所示的错误。
错误的任何原因?
FragmentTransaction类型中的replace(int, Fragment)方法不适用于参数(int, ExampleFragments)
我的主要 Activity 中的代码:
public void red(View view) {
android.app.FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragments fragment = new ExampleFragments();
fragmentTransaction.replace(R.id.frag, fragment);
fragmentTransaction.commit();
}
ExampleFragments.java
package com.example.learn.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ExampleFragments extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.blue_pill_frag, container, false);
}
}
这里:
package com.example.learn.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
最佳答案
这里的问题是你混合了 android.support.v4.app.Fragment
和 android.app.Fragment
。您需要将所有用途转换为使用支持库,这也意味着调用 getSupportFragmentManager()
。
类似这样的东西,例如:
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExampleFragments fragment = new ExampleFragments();
fragmentTransaction.replace(R.id.frag, fragment);
fragmentTransaction.commit();
需要注意的是,支持库 Fragment
和普通的 Fragment
是不可互换的。它们达到相同的目的,但在代码中不能相互替换。
关于java - fragment 添加或替换不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11619573/