片段添加或替换不起作用 [英] Fragment add or replace not working
问题描述
我正在使用此参考中的代码.
当我将该代码放入我的程序时,出现如下图所示的错误.
When I put in that code in my program I get an error as seen in the picture below.
错误有什么原因吗?FragmentTransaction 类型中的方法 replace(int, Fragment) 不适用于参数 (int, ExampleFragments)
来自我的主要活动的代码:
Code from my main 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
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.片段
.您需要转换所有用途以使用支持库,这也意味着调用getSupportFragmentManager()
.
The problem here is that you're mixing android.support.v4.app.Fragment
and android.app.Fragment
. You need to convert all uses to use the support library, which also means calling getSupportFragmentManager()
.
类似这样的东西,例如:
Something like this, for example:
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
不可互换.它们达到相同的目的,但在代码中不能相互替换.
It is important to note that the support library Fragment
and the normal Fragment
are NOT interchangeable. They achieve the same purpose, but they cannot be replaced with one another in code.
这篇关于片段添加或替换不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!