【问题标题】:Android Studio add Fragment in FragmentManagerAndroid Studio 在 FragmentManager 中添加 Fragment
【发布时间】:2020-12-08 15:39:50
【问题描述】:

我刚刚进入 Android 开发领域,我遵循了在官方 android 开发者文档网站上创建片段的标准指南。但是,当我尝试将我的简单片段添加到片段容器时,add() 方法声称我的 Fragment 类的传递参数不正确。

这是我的主要活动的 onCreate() 方法:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .setReorderingAllowed(true)
                    .add(R.id.fragment_container_view, ChatFragment.class, null)
                    .commit();
        }
    }

这是我的 Fragment 类:

public class ChatFragment extends Fragment {
    public ChatFragment() {
        super(R.layout.chat_layout);
    }
}

我得到的编译器错误是“必需类型:片段,提供:类”,虽然我只是从官方文档网站复制代码。也许自从他们写了这篇文章后发生了一些变化,但到目前为止我找不到解决方案。

我通常要做的是,我有底部导航栏,根据我点击的项目,应该显示另一个片段,我的代码中的上部片段是“标准”视图启动应用程序。

【问题讨论】:

  • 使用new ChatFragment()
  • 然后它说“提供:ChatFragment”
  • 请检查参数列表,了解您需要使用 Ctrl+P 传递给方法的内容

标签: java android android-studio android-fragments


【解决方案1】:

使用:

getSupportFragmentManager().beginTransaction()
                    .setReorderingAllowed(true)
                    .add(R.id.fragment_container_view, new ChatFragment(), null)
                    .commit();

【讨论】:

  • 我已经尝试过了,但它显示“必需类型:片段,提供:ChatFragment”
  • CharFragment 中的导入是什么?
  • androidx.fragment.app.Fragment、androidx.annotation.Nullable 和 android.os.Bundle
【解决方案2】:

试试下面的东西

getSupportFragmentManager().beginTransaction().add(R.id.fragment_container_view,new ChatFragment(),"ChatFragment").commit();

在聊天片段而不是构造函数中尝试在 onCreateView 中膨胀

 @Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.chat_layout, container, false);
}

【讨论】:

    猜你喜欢
    • 2021-04-09
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2014-03-01
    • 1970-01-01
    相关资源
    最近更新 更多