在Android应用程序中向活动添加新片段时出错

squ*_*les 4 android android-fragments

我正在关注Android开发者网站(教程)上的教程,我收到此错误:

FragmentTransaction类型中的方法add(int,Fragment)不适用于参数(int,DisplayMessageActivity.PlaceholderFragment)

我已经做了很多研究,似乎大多数人的问题是他们输入了错误的东西,但是我导入的android.app.Fragment是大多数人对这个错误的解决方案,并且DisplayMessageActivity.PlaceholderFragment是Fragment的扩展所以我认为类型应该匹配罚款(我也试过更换new PlaceholderFragment()new Fragment(),得到了同样的错误.我认为错误是从该文件的到来.

下面是我使用导入文件创建的新活动的代码; 任何帮助将不胜感激.

package com.example.myfirstapp;

import android.support.v7.app.ActionBarActivity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

public class DisplayMessageActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_message);

    if (savedInstanceState == null){
        //ERROR IS HERE
        getSupportFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

public static class PlaceholderFragment extends Fragment{
    public PlaceholderFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.activity_display_message, container, false);
        return rootView;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*uis 5

你应该getSupportFragmentManager()在处理android.support.v4.app.FragmentgetFragmentManager()处理时使用android.app.Fragment.
从您的示例中,您应该使用后者.

getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
Run Code Online (Sandbox Code Playgroud)