首页 > 解决方案 > 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>`

标签: androidgridviewkotlinfragmentcustom-adapter

解决方案


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

val adapter = GridviewAdapter(getContext(), example )

推荐阅读