Android Studio Fragment将上下文传递给自定义Gridview

问题描述 投票:0回答:2

如何使用自定义gridview制作片段?我尝试过活动,它从活动中传递了上下文,但我不知道如何使用Fragment。我试过“活动”但仍然从适配器得到null结果。

我的碎片:

   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

我们是CML

 `<?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>`
android gridview kotlin fragment custom-adapter
2个回答
0
投票

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

val adapter = GridviewAdapter(getContext(), example )

-1
投票

[**[![`[

enter link description here

] Qazxswpoi`] 1] 1 **] 1

© www.soinside.com 2019 - 2024. All rights reserved.