在 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 類并重寫相關方法來實現。