RecyclerView实现横向滚动效果
本文实例为大家分享了RecyclerView实现横向滚动效果的具体代码,供大家参考,具体内容如下
布局文件
Item
android:layout_width="100dp" android:layout_height="wrap_content" android:orientation="vertical" android:layout_margin="5dp">
适配器
publicclassRecyclerViewAdapterextendsRecyclerView.Adapter{ privateList animalList; privateintresource; publicRecyclerViewAdapter(List animalList,intresource){ this.animalList=animalList; this.resource=resource; } @NonNull @Override publicViewHolderonCreateViewHolder(@NonNullViewGroupparent,intviewType){ ViewitemView=LayoutInflater.from(parent.getContext()).inflate(resource,parent, false); ViewHolderholder=newViewHolder(itemView); returnholder; } @Override publicvoidonBindViewHolder(@NonNullViewHolderholder,intposition){ Animalanimal=animalList.get(position); holder.animalImag.setImageResource(animal.getImageId()); holder.animalName.setText(animal.getName()); } @Override publicintgetItemCount(){ returnanimalList.size(); } staticclassViewHolderextendsRecyclerView.ViewHolder{ ImageViewanimalImag; TextViewanimalName; publicViewHolder(ViewitemView){ super(itemView); animalImag=itemView.findViewById(R.id.iv_recyclerview_imag); animalName=itemView.findViewById(R.id.tv_recyclerview_name); } } }
核心代码
publicclassRecyclerViewActivityextendsAppCompatActivity{ privateListanimalList=newArrayList<>(); privateRecyclerViewrecyclerView; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler_view); recyclerView=findViewById(R.id.recyclerView_view); initAnimals(); LinearLayoutManagerlinearLayoutManager=newLinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); recyclerView.setLayoutManager(linearLayoutManager); RecyclerViewAdapteradapter=newRecyclerViewAdapter(animalList,R.layout.recyclerview_item); recyclerView.setAdapter(adapter); } //初始化动物数据 privatevoidinitAnimals(){ Animaldaxaing=newAnimal("大象",R.drawable.animal_one); animalList.add(daxaing); Animalshizi=newAnimal("袋鼠",R.drawable.animal_two); animalList.add(shizi); Animaldaishu=newAnimal("二哈",R.drawable.animal_three); animalList.add(daishu); Animallaohu=newAnimal("狮子",R.drawable.animal_four); animalList.add(laohu); Animalzhu=newAnimal("猪",R.drawable.animal_five); animalList.add(zhu); Animalsongshu=newAnimal("猴子",R.drawable.animal_six); animalList.add(songshu); Animalbaozi=newAnimal("豹子",R.drawable.animal_seven); animalList.add(baozi); Animalshayu=newAnimal("鲨鱼",R.drawable.animal_eight); animalList.add(shayu); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。