android - Android Studio Fragment 将上下文传递给自定义 Gridview
问题描述
如何使用自定义网格视图制作片段?我已经尝试过活动,它从活动中传递了上下文,但我不知道如何使用 Fragment。我已经尝试过“活动”,但我仍然从适配器得到空结果。
我的片段:
val example = listOf<String>(
"Product 1", "Product 2", "Product 3", "Product 4", "Product 5", "Product 6", "Product 7", "Product 8"
)
val adapter = GridviewAdapter(this, example )
grid_view.adapter = adapter
我的适配器:
class GridviewAdapter(private val context: Context, private val list_produk: List<String>) : BaseAdapter() {
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view: View = LayoutInflater.from(context).inflate(R.layout.custom_gridview_produk, parent, false)
val nama = view.findViewById<AppCompatTextView>(R.id.txt_nama)
nama.text = list_produk.get(position)
val harga = view.findViewById<AppCompatTextView>(R.id.txt_harga)
harga.text = "Rp 65.000".toString()
return view
}
错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.latihan.myapplication/com.latihan.myapplication.MainActivity}: java.lang.IllegalStateException: grid_viewmust not be null
我的 XML
`<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeFragment"
android:background="@android:color/darker_gray">
<GridView
android:layout_width="match_parent"
android:layout_height="wrap_content" android:numColumns="2"
android:id="@+id/grid_view"/>
</FrameLayout>`
解决方案
您是否通过 findViewById() 初始化了 gridview?并从片段传递上下文使用 getContext()....
val adapter = GridviewAdapter(getContext(), example )
推荐阅读
- stanford-nlp - CoreNLP:English_SD模型最后更新时间
- angular - LoginServices 单元测试
- java - 标题 ObservableField 默认为应用名称
- unit-testing - 模块
未找到转换选项中的 /node_modules/vue-jest - graph-theory - 图数据库中的边方向应该如何?
- node.js - 使用 npm init 时如何修复“ENOENT:没有这样的文件或目录”错误?
- javascript - 使用不同的窗口对象调用“Eval”
- android - Bluestacks 4 显示错误 System.BadImageFormatException
- android - 带有偏移量的滚动视图,模仿底部工作表
- c# - 无法在运行时更改材质颜色