我的列表只显示一行数据,即使预期的4行通过ViewHolder
。
RecyclerView
,RecyclerView.Adapter
和RecyclerView.ViewHolder
都在按照我的预期AFAICT运作。我看到正确的4行数据通过bind函数。但是,我只在列表中看到一行。好像LinearLayoutManager
没有正确地布置垂直方向的单元格。我不确定错过了什么。
class SongListFragment : Fragment() {
private lateinit var mediaProvider:MediaProvider
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mediaProvider = MediaLibraryTestSongProvider()
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
//TODO: how to inflate fragment using Kotlin extension?
val songListView = inflater.inflate(R.layout.fragment_song_list, container, false)
val songListRecyclerView = songListView.songListRecyclerView
songListRecyclerView.layoutManager = LinearLayoutManager( activity )
songListRecyclerView.adapter = SongListCellAdapter(mediaProvider.getSongs() )
return songListView
}
private inner class SongListCellAdapter(val songList:List<Song>) : RecyclerView.Adapter<SongListCellHolder>()
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : SongListCellHolder {
val inflater = LayoutInflater.from( activity )
val songCellView = inflater.inflate(R.layout.cell_song_list,parent,false)
val holder = SongListCellHolder( songCellView )
return holder
}
override fun onBindViewHolder(holder: SongListCellHolder, position: Int) {
holder.bind(songList[position])
}
override fun getItemCount(): Int {
return songList.size
}
}
private inner class SongListCellHolder(itemView:View) : RecyclerView.ViewHolder(itemView)
{
fun bind( song:Song ) = with(itemView) {
songTitle.text = song.title
songArtist.text = song.artist
}
}
}
答案 0 :(得分:2)
问题变得简单(一旦你知道答案)。我的单元格布局cell_song_list
有layout_height="match_content"
,导致每个单元格都是屏幕的大小。其他人在那里,但屏幕外,在模拟器上我没有滚动注意。
对于记录,这是我更正的单元格布局,顶级LinearLayout
使用layout_height="wrap_content"
,因此单元格大小正确。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/songTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textAppearance="@style/TextAppearance.AppCompat.Title"
tools:text="Title" />
<TextView
android:id="@+id/songArtist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Artist"
android:textAppearance="@style/TextAppearance.AppCompat.Caption" />
</LinearLayout>