2017-07-27 59 views
1

我的列表僅顯示單行數據,即使預期的4行通過ViewHolderRecyclerView與Kotlin不垂直佈局單元格

RecyclerView,RecyclerView.AdapterRecyclerView.ViewHolder都按我所期望的AFAICT工作。我看到正確的4行數據通過綁定函數傳遞。但是,我只在列表中看到一行。就好像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

是的,這是Kotlin擴展的語法。它取代了正常的findViewById()調用。 –

回答

2

問題原來很簡單(一旦你知道答案)。我的單元佈局cell_song_listlayout_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> 
+0

這是很常見的錯誤。 –