【问题标题】:android.support.v4.app.FragmentManager cannot converted to android.app.FragmentManagerandroid.support.v4.app.FragmentManager 无法转换为 android.app.FragmentManager
【发布时间】:2017-05-11 14:35:38
【问题描述】:

我是 Android 新手,我尝试在平板电脑中使用 Fragment。但我在 MainActivity.java 文件中遇到错误。

错误显示它需要'android.app.FragmentManager'而不是'android.support.v4.app.FragmentManager'。我检查了库,它是由Android Studio自动导入的。

我该如何解决?非常感谢!

package com.example.fragmenttest;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(this);
        replaceFragment(new RightFragment());
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.button:
                replaceFragment(new AnotherRightFragment());
                break;
            default:
                break;
        }
    }
    public void replaceFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.right_fragment,fragment);
        transaction.commit();
    }
}

【问题讨论】:

    标签: java android android-fragments


    【解决方案1】:

    变化:

    import android.app.Fragment;
    

    到:

    import android.support.v4.app.Fragment;
    

    【讨论】:

    • 对不起,它不起作用。它在 'new RightFragment()' 和 'new AnotherRightFragment()' 中添加了两个新错误。
    • 这些新错误可能是因为 RightFragment 和 AnotherRightFragment(我建议更好的命名约定)正在使用 android.app.Fragment;而不是 android.support.v4.app.Fragment;在所有片段中更改它,它应该可以工作@RealCR1
    【解决方案2】:

    您可能需要在 build/gradle 中包含 support v4 库

    【讨论】:

    • 我试过你的建议,但效果不好。
    【解决方案3】:

    更改
    import android.app.Fragment;
    import android.support.v4.app.FragmentActivity;

    【讨论】:

    • Ops,结果和 MichaelStoddart 的一样。
    猜你喜欢
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    相关资源
    最近更新 更多