Android Studio片段将上下文传递到自定义Gridview
如何使用自定义gridview制作片段? 我试过使用activity,它从activity传递了上下文,但我不知道如何使用Fragment。我尝试过使用“活动”,但仍然从适配器获得空结果 我的片段:Android Studio片段将上下文传递到自定义Gridview,android,gridview,kotlin,fragment,custom-adapter,Android,Gridview,Kotlin,Fragment,Custom Adapter,如何使用自定义gridview制作片段? 我试过使用activity,它从activity传递了上下文,但我不知道如何使用Fragment。我尝试过使用“活动”,但仍然从适配器获得空结果 我的片段: val example = listOf<String>( "Product 1", "Product 2", "Product 3", "Product 4", "Product 5", "Product 6", "Product 7", "Product 8"
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
我的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()
[**[[`[
]`]]**]你能补充一个问题吗?你在哪里定义网格视图(xml)以及如何在片段中使用它?不,我只称它为id,因为它可以用kotlin完成。是的,在java中,我可以使用getContext(),但我不知道如何使用Kotlin。您可以查看此链接,谢谢,但仍然会给我“grid_view不得为null”错误消息。这并没有提供问题的答案。
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.latihan.myapplication/com.latihan.myapplication.MainActivity}: java.lang.IllegalStateException: grid_viewmust not be null
`<?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>`
val adapter = GridviewAdapter(getContext(), example )