【发布时间】:2019-04-14 07:01:39
【问题描述】:
如何使用自定义网格视图制作片段? 我已经尝试过活动,它从活动中传递了上下文,但我不知道如何使用 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>`
【问题讨论】:
-
您能否补充一下定义grid_view(在xml中)以及如何在片段中使用它的问题?
标签: android gridview kotlin fragment custom-adapter