简体   繁体   English

将片段链接到活动错误

[英]Linking Fragment to Activity error

Im trying to attach a fragment to an activity, I've followed multiple tutorials and my code seems exactly the same (adapted to my app) than the ones in the tutorials and I cant find where my error is.我试图将一个片段附加到一个活动,我已经学习了多个教程,我的代码看起来与教程中的代码完全相同(适应我的应用程序),但我找不到我的错误在哪里。

  import android.os.Bundle;
  import android.support.design.widget.FloatingActionButton;
  import android.support.design.widget.Snackbar;
  import android.content.Intent;
  import android.support.v4.app.FragmentActivity;
  import android.view.View;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_comments);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.id_layout_comments, new CommentsFragment())
                .commit();
    }

I get the error at the ".add(R.id.id_layout_comments, new CommentsFragment())" and it says: "cant resolve method add(int, package.CommentsFragment)".我在“.add(R.id.id_layout_comments, new CommentsFragment())”处收到错误消息,它说:“无法解析方法 add(int, package.CommentsFragment)”。

This is the header of the class where I want to invoke the fragment:这是我要调用片段的类的标题:

 public class CommentsActivity extends FragmentActivity 

And this is the one of the fragment itself:这是片段本身之一:

 public class CommentsFragment extends Fragment

If you need any more information, let me know.如果您需要更多信息,请告诉我。 Thanks a lot in advanced!非常感谢先进!

Really you didn't need to extend FragmentActivity, just extend Activity is enough.真的你不需要扩展 FragmentActivity,扩展 Activity 就足够了。

Look at this example:看这个例子:

CommentsActivity:评论活动:

public class CommentsActivity extends FragmentActivity {
...
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_comments);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.id_layout_comments, new CommentsFragment())
                .commit();
    }
...
}

CommentsFragment:评论片段:

public class CommentsFragment extends Fragment{
...
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.your_resource, container, false);
    return view;
}
...
}

That's it :D就是这样:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM