Android Studio片段将上下文传递到自定义Gridview

时间:2019-04-14 07:01:39

标签: android gridview kotlin fragment custom-adapter

如何使用自定义gridview制作片段? 我已经尝试过活动,并且它通过活动传递了上下文,但是我不知道如何使用Fragment进行操作。我尝试使用“活动”,但仍然无法从适配器获得空结果。

我的片段:

make beaglebone_defconfig && make linux-headers
..
>>> linux-headers 4796173fc58688055a99a1cef19a839174067220 Downloading
Fetching all references
remote: Counting objects: 2298744

我的适配器:

   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
}

我的XML

  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.latihan.myapplication/com.latihan.myapplication.MainActivity}: java.lang.IllegalStateException: grid_viewmust not be null

2 个答案:

答案 0 :(得分:0)

您是否通过findViewById()初始化了gridview? 并从片段中传递上下文,请使用getContext()....

val adapter = GridviewAdapter(getContext(), example )

答案 1 :(得分:-1)

[** [![`[

  

enter link description here

] 1`] 1] 1 **] 1