无法使用v4.app.Fragment导入ResolveFragmentTransaction.add()

时间:2017-08-07 00:13:27

标签: java android android-fragments

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

  

无法解析方法' add(int,com.brewguide.android.coffeebrewguide.RecipeFragment)

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

MenuActivity.java

package com.brewguide.android.coffeebrewguide;
import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.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);
        }
    }

}

RecipeFragment.java

package com.brewguide.android.coffeebrewguide;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.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 个答案:

答案 0 :(得分:2)

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

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

使用支持片段

时,您需要getSupportFragmentManager()而不是getFragmentManager()