有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法解析碎片事务。使用v4添加()。应用程序。片段导入

我正在尝试动态创建一个片段,并收到以下错误消息:

Cannot resolve method 'add(int, com.brewguide.安卓.coffeebrewguide.RecipeFragment)

我查找到的其他答案表明,片段的库导入已关闭,因此我将库导入v4.app.Fragment而不是app.Fragment添加到片段和调用片段的活动中,问题并没有消失。下面是我的代码:

MenuActivity。java

package com.brewguide.安卓.coffeebrewguide;
import 安卓.support.v4.app.Fragment;
import 安卓.app.FragmentManager;
import 安卓.app.FragmentTransaction;
import 安卓.content.Intent;
import 安卓.os.Bundle;
import 安卓.support.v7.app.AppCompatActivity;
import 安卓.support.v7.widget.Toolbar;
import 安卓.widget.Toast;

public class MenuActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        int position;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //retrieves intent
        Intent i = getIntent();

        //fetches menu option that was selected.
        // 0  is the default
        position = i.getIntExtra("position", 0);

        // get an instance of FragmentTransaction from your Activity
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        //add a fragment
        RecipeFragment myFragment = new RecipeFragment();
        fragmentTransaction.add(R.id.myfragment, myFragment);
        fragmentTransaction.commit();

        switch (position){
            case 1:
                break;
            case 2:
                break;
            case 3:
                break;
            case 4:
                break;
            default:
                Toast toast = Toast.makeText(this,
                        "An Error has occurred.",
                        Toast.LENGTH_SHORT);
                toast.show();
                break;
        }
        if(getSupportActionBar()!= null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
    }

}

反射反射。java

package com.brewguide.安卓.coffeebrewguide;

import 安卓.os.Bundle;
import 安卓.support.v4.app.Fragment;
import 安卓.view.LayoutInflater;
import 安卓.view.View;
import 安卓.view.ViewGroup;

public class RecipeFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_recipe_layout, container, false);
    }
    public RecipeFragment(){}

}

共 (1) 个答案

  1. # 1 楼答案

    不仅仅是片段导入。。。您还需要支持片段管理器,而不是这些

    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    

    在使用支持片段时,需要getSupportFragmentManager()而不是getFragmentManager()