【问题标题】:Linking Fragment to Activity error将片段链接到活动错误
【发布时间】:2015-10-26 15:05:23
【问题描述】:

我试图将一个片段附加到一个活动中,我遵循了多个教程,我的代码似乎与教程中的代码完全相同(适用于我的应用程序),但我找不到我的错误所在。

  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();
    }

我在“.add(R.id.id_layout_cmets, new CommentsFragment())”处收到错误,它说:“cant resolve method add(int, package.CommentsFragment)”。

这是我要调用片段的类的标头:

 public class CommentsActivity extends FragmentActivity 

这是片段本身之一:

 public class CommentsFragment extends Fragment

如果您需要更多信息,请告诉我。非常感谢!

【问题讨论】:

  • public class CommentsFragment extends Fragment ...明显的问题:哪个Fragment? ...本地或来自支持库? ...
  • 支持库中的@Selvin Fragment 类
  • 那么这样的错误是不可能的...
  • @Selvin 我希望这不可能,但肯定是的
  • 编程不是什么魔法......

标签: java android android-fragments fragment


【解决方案1】:

真的不需要扩展FragmentActivity,扩展Activity就够了。

看这个例子:

评论活动:

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();
    }
...
}

评论片段:

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;
}
...
}

就是这样:D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多