片段添加或替换不起作用

2024-03-06

我正在使用这里的代码参考。 http://developer.android.com/guide/components/fragments.html

When I put in that code in my program I get an error as seen in the picture below. enter image description here

有什么错误原因吗?The method replace(int, Fragment) in the type FragmentTransaction is not applicable for the arguments (int, ExampleFragments)

我的主要活动中的代码:

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();
    }

示例Fragments.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);
    }
}

Here:

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 and 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不可互换。它们实现了相同的目的,但在代码中不能相互替换。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

片段添加或替换不起作用 的相关文章

随机推荐