androidx.recyclerview.widget.RecyclerView的使用方法

不飞则已,一飞冲天;不鸣则已,一鸣惊人。这篇文章主要讲述androidx.recyclerview.widget.RecyclerView的使用方法相关的知识,希望能为你提供帮助。
首先需要在布局里添加一下组件

< androidx.recyclerview.widget.RecyclerView android:id="@+id/recipe_list_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="100dp"> < /androidx.recyclerview.widget.RecyclerView>

【androidx.recyclerview.widget.RecyclerView的使用方法】 
然后再代码中初始化
private lateinit var recyclerView: RecyclerView private lateinit var viewManager: RecyclerView.LayoutManager private lateinit var viewAdapter: RecyclerView.Adapter< *>



fun initListView() {
val viewManager = LinearLayoutManager(MyApplication.getContext())
viewManager.orientation = LinearLayoutManager.HORIZONTAL
this.viewManager = viewManager
viewAdapter = MyAdapter(forecast)

recyclerView = binding.recipeListView.apply {
layoutManager = viewManager
adapter = viewAdapter
setHasFixedSize(true)
}
}


//创建Adapt

class MyAdapter(var list: MutableList< Forecast> ) :
RecyclerView.Adapter< MyAdapter.ViewListViewHolder> () {

//新建ViewHolder
class ViewListViewHolder(var viewItem: View) : RecyclerView.ViewHolder(viewItem) {}

private val inflater: LayoutInflater =
MyApplication.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewListViewHolder {
var view = inflater.inflate(R.layout.forecast, parent, false)

return ViewListViewHolder(view)
}

override fun getItemCount(): Int {
return list.size
}

override fun onBindViewHolder(holder: ViewListViewHolder, position: Int) {

holder.viewItem.findViewById< TextView> (R.id.text_weekday_tem_one).apply {
this.text = list[position].tmp_max + "° " + "/" + list[position].tmp_min + "° "
this.typeface = MainActivity.getEnglishFontsOne()
}

holder.viewItem.findViewById< TextView> (R.id.text_weekday_one).apply {
val df = SimpleDateFormat("yyyy-MM-dd")
val date = df.parse(list[position].date)
this.text = SpUtils.getWeek(date)
this.typeface = MainActivity.getMyFonts()
}

holder.viewItem.findViewById< ImageView> (R.id.image_weekday_one).apply {
this.setImageResource(MyIconUtils.getWeatherIcon(list[position].cond_code_d))
}
}
}



 

    推荐阅读