在 Android 中,为 ItemList 添加动画效果可以使用 RecyclerView 和 ItemAnimator
dependencies {
implementation 'com.android.support:recyclerview-v7:28.0.0'
}
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class MyListItem {
private String title;
public MyListItem(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView titleTextView;
public MyViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.text_view_title);
}
}
public class MyListAdapter extends RecyclerView.Adapter<MyViewHolder> {
private List<MyListItem> myListItems;
public MyListAdapter(List<MyListItem> myListItems) {
this.myListItems = myListItems;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
MyListItem currentItem = myListItems.get(position);
holder.titleTextView.setText(currentItem.getTitle());
}
@Override
public int getItemCount() {
return myListItems.size();
}
}
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
List<MyListItem> myListItems = new ArrayList<>();
// 向 myListItems 添加数据
MyListAdapter adapter = new MyListAdapter(myListItems);
recyclerView.setAdapter(adapter);
现在,当你更新列表数据并调用 adapter.notifyDataSetChanged()
时,RecyclerView 将自动应用默认的动画效果。如果需要自定义动画效果,可以通过扩展 ItemAnimator 类并重写相关方法来实现。