【问题标题】:How can I implement a RecyclerView and a CardView into a fragment?如何将 RecyclerView 和 CardView 实现到片段中?
【发布时间】:2019-09-28 02:30:04
【问题描述】:

我是 Android Studio 的新手,我正在构建一个应用程序,该应用程序的侧边栏带有指向片段的图标。在学习了几个教程之后,实现了侧边栏,每个图标都指向一个片段。在其中一个片段中,我想设置一个 RecyclerView 和一个 CardView ,它们能够创建新条目并删除它们。我尝试按照 Flow 的教程 here 中的编码进行操作,但是,他在 MainActivity 中实现它,而不是片段。我尝试使用相同的代码将它们放入片段中,这似乎工作正常,直到他写道
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent);

还有其他方法来定义这个充气机吗?或者我也可以参考其他教程?

【问题讨论】:

  • 这也应该在片段中工作,假设 parent 是某种 ViewGroup...

标签: android android-layout android-fragments android-recyclerview android-cardview


【解决方案1】:

语法有什么问题!?您还应该通过构造函数在适配器中传递上下文变量。您可以使用 context 变量而不是 parent.getContext() 来访问所有活动方法。如果您仍然感到困惑,也许粘贴有问题的代码,您将帮助我们给出更好的解释。 您还说您的回收站和卡片视图有问题,可能您的意思是说您无法使用findViewById 访问回收站视图或卡片视图?如果是这种情况,您可以使用视图对象访问它们。示例:

View view =  LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent);
RecyclerView recyclerview = view.findViewById(R.id.recycler);

【讨论】:

    【解决方案2】:

    attach to root参数设置为false 如下放大您的视图

    View view =  LayoutInflater.from(parent.getContext()).inflate(R.layout.example_item, parent,false);
    

    【讨论】:

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