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

Posted 天也高 地也厚

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>

 

然后再代码中初始化

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))
}
}
}


 

以上是关于androidx.recyclerview.widget.RecyclerView的使用方法的主要内容,如果未能解决你的问题,请参考以下文章