對於任何RecyclerView,你需要具有所有的內部animal_ticket
列出的意見自己ViewHolder類。
基本上,它的工作原理是這樣的:
1)創建ViewHolder是「持有」你們要顯示的項目的意見;
2)將ViewHolder綁定到RecyclerView併爲其中的視圖賦值;
下面是一個例子適配器我寫道:
class MyActivity : Activity() {
//users is the list we're going to use to get information for the views
val users = ArrayList<User>()
//...getting user information
//.. your activity stuff here
//Creating our adapter
/*
Note that to extend the RecyclerView.Adapter, you need to specify a
ViewHolder. The code becomes much easier to manage if you just put the
ViewHolder inside your adapter.
*/
inner class MyAdapter : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {
//This is the view holder
inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
//Here you declare your views and get them from the itemView
//The itemView is one that is passed each time to the RecyclerView
//(the items inside your XML layout file)
internal val userImageView = itemView.findViewById(R.id.userImage)
internal val userFullName = itemView.findViewById(R.id.userName)
}
//This is where you return your own ViewHolder with your layout
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
//user_list_item.xml is below
val itemView = layoutInflater.inflate(R.layout.user_list_item, parent, false))
return MyViewHolder(itemView)
}
//In here is where you want to set your values for the views
override fun onBindViewHolder(holder: SentRequestViewHolder, position: Int) {
val currentUser = users[position]
holder.userImage.drawable = currentUser.drawable
holder.userFullName.text = currentUser.name
}
//You must override this method as well for the adapter to work properly
override fun getItemCount() = users.size
}
你必須重寫這些方法使用RecyclerView.Adapter
當這裏是user_list_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp">
<ImageView
android:id="@+id/userImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/userName"
android:layout_below="@id/userImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
很好的意見,但考慮到這個問題使用'override fun getView',OP很可能使用'ListView'''''而不是'RecyclerView''''RecyclerView.Adapter'。 – ephemient