java - fragment 添加或替换不起作用

标签 java android android-fragments

我正在使用 reference. 中的代码

当我在我的程序中输入该代码时,出现如下图所示的错误。 enter image description here

错误的任何原因? 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.Fragmentandroid.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/

相关文章:

java - 两次之间的差异始终返回 2 或更大

android - 尝试调用虚方法'void android.widget.ListView.setAdapter

java.lang.NullPointerException : Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference 异常

java - 求 200 万以内的素数之和

java - "Migrate"从属性的经典 java.util.Date 类型到 java.time 的等效类型

java - KeyBindings 卡在 actionPerformed() 上

android - Animation.AnimationListener 和 Animator.AnimatorListener 有什么区别?

java - getApplicationContext() 返回 null,但在其他 Activity 中有效

android-fragments - 在事件中从 onLoadFinished 提交片段

android - 在 View 寻呼机中查看上一个 View 和下一个 View 之间的重叠