### Setup Heterogeneous RecyclerView Adapter in Android Activity (Kotlin) Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Configures a 'ListDelegationAdapter' in an 'AppCompatActivity' to manage a heterogeneous list of 'FeedItem's. It sets up click listeners for each item type and displays a 'Toast' or navigates to a URL upon interaction. ```kotlin // Activity class FeedActivity : AppCompatActivity() { private lateinit var adapter: ListDelegationAdapter> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_feed) adapter = ListDelegationAdapter( postDelegate { post -> Toast.makeText(this, "Liked post by ${post.author}", Toast.LENGTH_SHORT).show() }, advertisementDelegate { ad -> // Open ad URL startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(ad.targetUrl))) }, userRecommendationDelegate { user -> Toast.makeText(this, "Following ${user.username}", Toast.LENGTH_SHORT).show() } ) val recyclerView = findViewById(R.id.feed_recycler) recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = adapter // Load data loadFeedData() } private fun loadFeedData() { val feedItems = listOf( Post(1, "John Doe", "Hello World!", System.currentTimeMillis()), Advertisement(2, "https://example.com/ad.jpg", "https://example.com"), Post(3, "Jane Smith", "Great day!", System.currentTimeMillis()), UserRecommendation(4, "awesome_user", 1500), Post(5, "Bob Wilson", "Check this out!", System.currentTimeMillis()) ) adapter.items = feedItems } private fun formatTimestamp(timestamp: Long): String { val now = System.currentTimeMillis() val diff = now - timestamp return when { diff < 60000 -> "Just now" diff < 3600000 -> "${diff / 60000}m ago" diff < 86400000 -> "${diff / 3600000}h ago" else -> "${diff / 86400000}d ago" } } } ``` -------------------------------- ### Create Snake List Item Adapter Delegate - Java Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Example of creating a type-safe adapter delegate for handling 'Snake' items using AbsListItemAdapterDelegate. This simplifies delegate creation for list-based data sources. ```java public class SnakeListItemAdapterDelegate extends AbsListItemAdapterDelegate { private LayoutInflater inflater; public SnakeListItemAdapterDelegate(Activity activity) { inflater = activity.getLayoutInflater(); } @Override protected boolean isForViewType(@NonNull DisplayableItem item, @NonNull List items, int position) { return item instanceof Snake; } @NonNull @Override public SnakeViewHolder onCreateViewHolder(@NonNull ViewGroup parent) { return new SnakeViewHolder(inflater.inflate(R.layout.item_snake, parent, false)); } @Override protected void onBindViewHolder(@NonNull Snake snake, @NonNull SnakeViewHolder vh, @Nullable List payloads) { vh.name.setText(snake.getName()); vh.race.setText(snake.getRace()); } static class SnakeViewHolder extends RecyclerView.ViewHolder { public TextView name; public TextView race; public SnakeViewHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.name); race = (TextView) itemView.findViewById(R.id.race); } } } ``` -------------------------------- ### Create Cat Adapter Delegate - Java Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Example of creating a custom adapter delegate for handling 'Cat' items in a RecyclerView. It extends the base AdapterDelegate class and defines how to create a ViewHolder and bind data for Cat items. ```java public class CatAdapterDelegate extends AdapterDelegate> { private LayoutInflater inflater; public CatAdapterDelegate(Activity activity) { inflater = activity.getLayoutInflater(); } @Override protected boolean isForViewType(@NonNull List items, int position) { return items.get(position) instanceof Cat; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent) { return new CatViewHolder(inflater.inflate(R.layout.item_cat, parent, false)); } @Override public void onBindViewHolder(@NonNull List items, int position, @NonNull RecyclerView.ViewHolder holder, @Nullable List payloads) { CatViewHolder vh = (CatViewHolder) holder; Cat cat = (Cat) items.get(position); vh.name.setText(cat.getName()); } static class CatViewHolder extends RecyclerView.ViewHolder { public TextView name; public CatViewHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.name); } } } ``` -------------------------------- ### Kotlin DSL adapterDelegateLayoutContainer with Synthetics Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt DSL leveraging synthetic properties for direct view access without findViewById or ViewBinding setup. Depends on Kotlin Android Extensions plugin. Inputs include layout ID and click handlers; outputs delegate for binding text and images. Limitation: Deprecated in favor of ViewBinding; requires plugin configuration. ```kotlin fun dogAdapterDelegate() = adapterDelegateLayoutContainer(R.layout.item_dog) { // Access views directly via synthetic properties (no findViewById needed) name.setOnClickListener { Toast.makeText(context, "Woof from ${item.name}!", Toast.LENGTH_SHORT).show() } breed.setOnClickListener { Log.d("DogDelegate", "Breed: ${item.breed}") } bind { name.text = item.name breed.text = item.breed age.text = "Age: ${item.age}" image.setImageResource(R.drawable.dog_icon) } } ``` -------------------------------- ### Create AnimalAdapter with delegates in Java Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Implementation of an AnimalAdapter using AdapterDelegatesManager to compose multiple delegate components. Shows how to manage view types and delegate binding. ```java public class AnimalAdapter extends RecyclerView.Adapter { private AdapterDelegatesManager> delegatesManager; private List items; public AnimalAdapter(Activity activity, List items) { this.items = items; delegatesManager = new AdapterDelegatesManager<>(); delegatesManager.addDelegate(new CatAdapterDelegate(activity)) .addDelegate(new DogAdapterDelegate(activity)) .addDelegate(new GeckoAdapterDelegate(activity)); delegatesManager.addDelegate(23, new SnakeAdapterDelegate(activity)); } @Override public int getItemViewType(int position) { return delegatesManager.getItemViewType(items, position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return delegatesManager.onCreateViewHolder(parent, viewType); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { delegatesManager.onBindViewHolder(items, position, holder); } @Override public int getItemCount() { return items.size(); } } ``` -------------------------------- ### Create AdapterDelegate with ViewBinding support Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Demonstrates the ViewBinding/DataBinding DSL to inflate a binding class and bind Cat data. This approach provides type‑safe view references and integrates with modern Android view binding practices. ```kotlin fun cat2AdapterDelegate(itemClickedListener : (Cat) -> Unit) = adapterDelegateViewBinding( { layoutInflater, root -> ItemCatBinding.inflate(layoutInflater, root, false) } ) { binding.name.setOnClickListener { itemClickedListener(item) } bind { binding.name.text = item.name } } ``` -------------------------------- ### Create basic AdapterDelegate with Kotlin DSL Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Defines an AdapterDelegate for a Cat item using the standard DSL. It inflates the item layout, sets up a click listener, and binds the Cat's name to a TextView. Suitable for projects without synthetic properties or ViewBinding. ```kotlin fun catAdapterDelegate(itemClickedListener : (Cat) -> Unit) = adapterDelegate(R.layout.item_cat) { // This is the initializer block where you initialize the ViewHolder. // Its called one time only in onCreateViewHolder. // this is where you can call findViewById() and setup click listeners etc. val name : TextView = findViewById(R.id.name) name.setClickListener { itemClickedListener(item) } // Item is automatically set for you. It's set lazily though (set in onBindViewHolder()). So only use it for deferred calls like clickListeners. bind { diffPayloads -> // diffPayloads is a List containing the Payload from your DiffUtils // This is called anytime onBindViewHolder() is called name.text = item.name // Item is of type Cat and is the current bound item. } } ``` -------------------------------- ### Configure Gradle Dependencies for AdapterDelegates Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt This code snippet shows the Gradle configuration required to use AdapterDelegates in your Android project. It includes the main library and optional dependencies such as Kotlin DSL, view binding, layout containers, and paging integration. Ensure you have RecyclerView and Paging runtime dependencies if using paging. ```gradle // build.gradle (app module) dependencies { // Core library (required) implementation 'com.hannesdorfmann:adapterdelegates4:4.3.2' // Kotlin DSL (optional, for Kotlin projects) implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl:4.3.2' // Kotlin DSL with ViewBinding support (optional) implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl-viewbinding:4.3.2' // Kotlin DSL with LayoutContainer support (optional, for synthetic properties) implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl-layoutcontainer:4.3.2' // Paging library integration (optional) implementation 'com.hannesdorfmann:adapterdelegates4-pagination:4.3.2' // Required dependencies (usually already in project) implementation 'androidx.recyclerview:recyclerview:1.2.1' implementation 'androidx.paging:paging-runtime:3.0.0' // If using pagination } ``` -------------------------------- ### Pagination Library Integration Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Shows the Gradle dependency for adding pagination support to AdapterDelegates. The pagination library provides PagedListDelegationAdapter for integrating with Android Architecture Components paging library. ```gradle implementation 'com.hannesdorfmann:adapterdelegates4-pagination:4.3.2' ``` -------------------------------- ### Kotlin DSL adapterDelegate Function Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Creates adapter delegates using inline functions and reified generics for minimal boilerplate. Depends on Kotlin extensions and RecyclerView layout. Inputs include layout ID and click listeners; outputs a delegate for binding item data. Supports bind for payloads and onViewRecycled for cleanup; limitation: Manual view finding without type safety. ```kotlin fun catAdapterDelegate(itemClickedListener: (Cat) -> Unit) = adapterDelegate(R.layout.item_cat) { val name: TextView = findViewById(R.id.name) val icon: ImageView = findViewById(R.id.icon) name.setOnClickListener { itemClickedListener(item) } bind { diffPayloads -> name.text = item.name icon.setImageResource(R.drawable.cat) } onViewRecycled { icon.setImageDrawable(null) } } // Usage val adapter = ListDelegationAdapter>( catAdapterDelegate { cat -> Toast.makeText(context, "Clicked ${cat.name}", Toast.LENGTH_SHORT).show() }, dogAdapterDelegate(), snakeAdapterDelegate() ) recyclerView.adapter = adapter adapter.items = listOf(Cat("Fluffy"), Dog("Rex"), Cat("Whiskers")) ``` -------------------------------- ### Create CatAdapterDelegate in Java Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Implementation of an AdapterDelegate for Cat items in Java. Includes view type checking, view holder creation, and data binding logic. ```java public class CatAdapterDelegate extends AdapterDelegate> { private LayoutInflater inflater; public CatAdapterDelegate(Activity activity) { inflater = activity.getLayoutInflater(); } @Override public boolean isForViewType(@NonNull List items, int position) { return items.get(position) instanceof Cat; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent) { return new CatViewHolder(inflater.inflate(R.layout.item_cat, parent, false)); } @Override public void onBindViewHolder(@NonNull List items, int position, @NonNull RecyclerView.ViewHolder holder, @Nullable List payloads) { CatViewHolder vh = (CatViewHolder) holder; Cat cat = (Cat) items.get(position); vh.name.setText(cat.getName()); } static class CatViewHolder extends RecyclerView.ViewHolder { public TextView name; public CatViewHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.name); } } } ``` -------------------------------- ### Integrate with Android Paging Library Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Implements PagedListDelegationAdapter for efficient loading and display of large datasets with pagination support. Requires Android Paging Library dependencies and proper DiffUtil configuration for item comparison. Supports automatic list updates and efficient memory usage for large datasets. ```java public class PagedAdapter extends PagedListDelegationAdapter { public PagedAdapter() { super(DIFF_CALLBACK); delegatesManager .addDelegate(new CatAdapterDelegate()) .addDelegate(new DogAdapterDelegate()) .addDelegate(new LoadingAdapterDelegate()); } private static final DiffUtil.ItemCallback DIFF_CALLBACK = new DiffUtil.ItemCallback() { @Override public boolean areItemsTheSame(@NonNull Animal oldItem, @NonNull Animal newItem) { return oldItem.getId() == newItem.getId(); } @Override public boolean areContentsTheSame(@NonNull Animal oldItem, @NonNull Animal newItem) { return oldItem.equals(newItem); } }; } // Usage with Paging Library public class AnimalViewModel extends ViewModel { public LiveData> animals; public AnimalViewModel(AnimalDao dao) { PagedList.Config config = new PagedList.Config.Builder() .setPageSize(20) .setPrefetchDistance(10) .setEnablePlaceholders(false) .build(); animals = new LivePagedListBuilder<>(dao.getAllAnimals(), config).build(); } } // In Activity/Fragment AnimalViewModel viewModel = ViewModelProviders.of(this).get(AnimalViewModel.class); PagedAdapter adapter = new PagedAdapter(); recyclerView.setAdapter(adapter); viewModel.animals.observe(this, pagedList -> { adapter.submitList(pagedList); }); ``` -------------------------------- ### ListDelegationAdapter: Simplify List-based Adapters Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Demonstrates how to extend ListDelegationAdapter to reduce boilerplate code when working with List-based data sources. This class provides built-in delegates manager and item management, eliminating the need to manually implement AdapterDelegatesManager integration. ```java public class AnimalAdapter extends ListDelegationAdapter> { public AnimalAdapter(Activity activity, List items) { // DelegatesManager is a protected Field in ListDelegationAdapter delegatesManager.addDelegate(new CatAdapterDelegate(activity)) .addDelegate(new DogAdapterDelegate(activity)) .addDelegate(new GeckoAdapterDelegate(activity)) .addDelegate(23, new SnakeAdapterDelegate(activity)); // Set the items from super class. set_items(items); } } ``` -------------------------------- ### Create Adapter Delegates for RecyclerView Items in Kotlin Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Implements adapter delegates for 'Post', 'Advertisement', and 'UserRecommendation' using the adapter delegates library. Each delegate handles binding data, setting click listeners, and managing view recycling for its respective item type. ```kotlin // Delegates fun postDelegate(onLikeClick: (Post) -> Unit) = adapterDelegateViewBinding( { inflater, parent -> ItemPostBinding.inflate(inflater, parent, false) } ) { binding.likeButton.setOnClickListener { onLikeClick(item) } bind { binding.authorName.text = item.author binding.postContent.text = item.content binding.timestamp.text = formatTimestamp(item.timestamp) } } fun advertisementDelegate(onAdClick: (Advertisement) -> Unit) = adapterDelegateViewBinding( { inflater, parent -> ItemAdBinding.inflate(inflater, parent, false) } ) { itemView.setOnClickListener { onAdClick(item) } bind { Glide.with(context) .load(item.imageUrl) .into(binding.adImage) } onViewRecycled { Glide.with(context).clear(binding.adImage) } } fun userRecommendationDelegate(onFollowClick: (UserRecommendation) -> Unit) = adapterDelegateViewBinding( { inflater, parent -> ItemUserRecommendationBinding.inflate(inflater, parent, false) } ) { binding.followButton.setOnClickListener { onFollowClick(item) } bind { binding.username.text = item.username binding.followerCount.text = "${item.followers} followers" } } ``` -------------------------------- ### Add AdapterDelegates Kotlin DSL dependencies (Gradle) Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Include the required artifacts in your Gradle build file to use the Kotlin DSL and optional LayoutContainer or ViewBinding extensions. These dependencies provide the adapterDelegate functions and related utilities. ```groovy implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl:4.3.2'; implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl-layoutcontainer:4.3.2'; implementation 'com.hannesdorfmann:adapterdelegates4-kotlin-dsl-viewbinding:4.3.2'; ``` -------------------------------- ### AsyncListDifferDelegationAdapter: Background Diff Calculation Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Demonstrates AsyncListDifferDelegationAdapter which combines AdapterDelegates with Android's AsyncListDiffer for automatic background diff calculation and item animations. This eliminates the need to manually call notify* methods and handles list updates efficiently. ```java public class DiffAdapter extends AsyncListDifferDelegationAdapter { public DiffAdapter() { super(DIFF_CALLBACK) // Your diff callback for diff utils delegatesManager .addDelegate(new DogAdapterDelegate()); .addDelegate(new CatAdapterDelegate()); } } ``` -------------------------------- ### Add AdapterDelegates SNAPSHOT dependency in Groovy Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Adds the SNAPSHOT version of AdapterDelegates library dependency to a Gradle project. Requires adding the Sonatype snapshot repository. ```groovy implementation 'com.hannesdorfmann:adapterdelegates4:4.3.3-SNAPSHOT' ``` ```groovy allprojects { repositories { ... maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } } ``` -------------------------------- ### Implement custom conditional logic for delegate selection Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Creates adapter delegates with custom 'on' conditions for advanced type checking beyond simple instanceof checks. Enables conditional rendering based on item properties, position, or list context. Written in Kotlin using adapterDelegate DSL syntax with lambda expressions for condition evaluation. ```kotlin // Delegate that only handles featured cats fun featuredCatDelegate() = adapterDelegate( layout = R.layout.item_featured_cat, on = { item: Animal, items: List, position: Int -> item is Cat && item.isFeatured } ) { val badge: TextView = findViewById(R.id.featured_badge) bind { name.text = item.name badge.visibility = View.VISIBLE badge.text = "⭐ Featured" } } // Delegate that handles first item differently fun headerItemDelegate() = adapterDelegate( layout = R.layout.item_dog_header, on = { item: Animal, items: List, position: Int -> item is Dog && position == 0 } ) { bind { headerText.text = "Dogs Section" name.text = item.name } } // Usage val adapter = ListDelegationAdapter>( featuredCatDelegate(), headerItemDelegate(), catDelegate(), // Regular cats dogDelegate() // Regular dogs ) ``` -------------------------------- ### Compose RecyclerView adapter multiple AdapterDelegates Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Creates a ListDelegationAdapter by registering several AdapterDelegate instances for different animal types. This final composition step wires together the previously defined delegates into a functional. ```kotlin val adapter = ListDelegationAdapter>( catAdapterDelegate(...), dogAdapterDelegate(), snakeAdapterDelegate() ) ``` -------------------------------- ### Kotlin DSL adapterDelegateViewBinding with ViewBinding Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Type-safe DSL using ViewBinding to avoid findViewById and enable compile-time checks. Depends on generated Binding classes and layout inflater. Inputs are binding inflater and event handlers; outputs delegate with bind for data and lifecycle callbacks. Limitation: Requires ViewBinding enabled in build.gradle. ```kotlin fun cat2AdapterDelegate() = adapterDelegateViewBinding( { layoutInflater, root -> ItemCatBinding.inflate(layoutInflater, root, false) } ) { binding.name.setOnClickListener { Log.d("CatDelegate", "Clicked on ${item.name}") Toast.makeText(context, "Meow from ${item.name}", Toast.LENGTH_SHORT).show() } bind { diffPayloads -> binding.name.text = item.name binding.icon.setImageResource(R.drawable.cat_icon) binding.description.text = "Age: ${item.age} years" } onViewAttachedToWindow { Log.d("CatDelegate", "${item.name} attached to window") } onViewDetachedFromWindow { Log.d("CatDelegate", "${item.name} detached from window") } } ``` -------------------------------- ### Implementing AsyncListDifferDelegationAdapter with DiffUtil (Java) Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt AsyncListDifferDelegationAdapter extends RecyclerView.Adapter with AsyncListDiffer for background DiffUtil computations, enabling efficient animations on list updates. It depends on DiffUtil.ItemCallback for item comparison and payload changes; inputs are lists of DiffItem, outputs are updated RecyclerView states with optional callbacks. Limitations include requiring custom DiffItem classes with IDs and hashes for diffing. ```java public class AsyncListDifferAdapter extends AsyncListDifferDelegationAdapter { public AsyncListDifferAdapter() { super(DIFF_CALLBACK); delegatesManager .addDelegate(new DiffDogAdapterDelegate()) .addDelegate(new DiffCatAdapterDelegate()) .addDelegate(new DiffAdvertisementDelegate()); } private static final DiffUtil.ItemCallback DIFF_CALLBACK = new DiffUtil.ItemCallback() { @Override public boolean areItemsTheSame(@NonNull DiffItem oldItem, @NonNull DiffItem newItem) { return oldItem.getItemId() == newItem.getItemId(); } @Override public boolean areContentsTheSame(@NonNull DiffItem oldItem, @NonNull DiffItem newItem) { return oldItem.getItemHash() == newItem.getItemHash(); } @Nullable @Override public Object getChangePayload(@NonNull DiffItem oldItem, @NonNull DiffItem newItem) { // Return payload for partial updates if (!oldItem.getName().equals(newItem.getName())) { return "NAME_CHANGED"; } return null; } }; } // Usage in Activity AsyncListDifferAdapter adapter = new AsyncListDifferAdapter(); recyclerView.setAdapter(adapter); // Initial data List initialData = Arrays.asList( new DiffCat(1, "Fluffy"), new DiffDog(2, "Rex") ); adapter.setItems(initialData); // Update data - diff calculated automatically on background thread List updatedData = Arrays.asList( new DiffCat(1, "Fluffy Updated"), new DiffDog(2, "Rex"), new DiffCat(3, "New Cat") ); adapter.setItems(updatedData, () -> { // Callback after diff is committed Log.d("Adapter", "List updated successfully"); }); ``` -------------------------------- ### ListDelegationAdapter with Delegates in Java Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Extends ListDelegationAdapter to handle List by adding type-specific delegates and a fallback. Depends on RecyclerView and custom delegate classes like GeckoAdapterDelegate. Inputs are activity context and item list; outputs a configured adapter for RecyclerView. Limitation: Requires manual delegate implementation for each item type. ```java public class ReptilesAdapter extends ListDelegationAdapter> { public ReptilesAdapter(Activity activity, List items) { // Add delegates for different types this.delegatesManager.addDelegate(new GeckoAdapterDelegate(activity)); this.delegatesManager.addDelegate(new SnakeListItemAdapterDelegate(activity)); // Set fallback for unknown types this.delegatesManager.setFallbackDelegate(new ReptilesFallbackDelegate(activity)); setItems(items); } } // Usage in Activity RecyclerView recyclerView = findViewById(R.id.recycler_view); List items = Arrays.asList( new Gecko("Gecko 1"), new Snake("Snake 1", "Python"), new Gecko("Gecko 2"), new Snake("Snake 2", "Cobra") ); ReptilesAdapter adapter = new ReptilesAdapter(this, items); recyclerView.setAdapter(adapter); ``` -------------------------------- ### Define Heterogeneous List Data Models in Kotlin Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Defines sealed class 'FeedItem' with data classes 'Post', 'Advertisement', and 'UserRecommendation' to represent different types of items in a heterogeneous list. Each item has a unique 'id'. ```kotlin // Data models sealed class FeedItem { abstract val id: Long } data class Post( override val id: Long, val author: String, val content: String, val timestamp: Long ) : FeedItem() data class Advertisement( override val id: Long, val imageUrl: String, val targetUrl: String ) : FeedItem() data class UserRecommendation( override val id: Long, val username: String, val followers: Int ) : FeedItem() ``` -------------------------------- ### Customize item matching with on‑lambda in AdapterDelegate Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Shows how to provide a custom `on` lambda to determine whether a delegate should handle a given item, e.g., only handling Cats at position zero. This enables fine‑grained control beyond the default instanceof check. ```kotlin adapterDelegate ( layout = R.layout.item_cat, on = { item: Animal, items: List, position: Int -> if (item is Cat && position == 0) true // return true: this adapterDelegate handles it else false // return false } ){ ... bind { ... } } ``` -------------------------------- ### AbsListItemAdapterDelegate: Type-Safe Item Handling Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Shows how to use AbsListItemAdapterDelegate to eliminate manual casting of list items and ViewHolders. This generic-based approach provides type safety at compile time and reduces boilerplate code for common adapter delegate patterns. ```java public class CatListItemAdapterDelegate extends AbsListItemAdapterDelegate { private LayoutInflater inflater; public CatAdapterDelegate(Activity activity) { inflater = activity.getLayoutInflater(); } @Override public boolean isForViewType(Animal item, List items, int position) { return item instanceof Cat; } @Override public CatViewHolder onCreateViewHolder(ViewGroup parent) { return new CatViewHolder(inflater.inflate(R.layout.item_cat, parent, false)); } @Override public void onBindViewHolder(Cat item, CatViewHolder vh, @Nullable List payloads) { vh.name.setText(item.getName()); } static class CatViewHolder extends RecyclerView.ViewHolder { public TextView name; public CatViewHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.name); } } } ``` -------------------------------- ### Add AdapterDelegates dependency in Groovy Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Adds the AdapterDelegates library dependency to a Gradle project. This is the stable version available on Maven Central. ```groovy implementation 'com.hannesdorfmann:adapterdelegates4:4.3.2' ``` -------------------------------- ### Create AdapterDelegate using LayoutContainer (synthetic properties) Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Uses the LayoutContainer variant to avoid manual view lookups by leveraging Kotlin Android Extensions synthetic properties. The delegate directly accesses the name view and binds data, simplifying view handling. ```kotlin fun catAdapterDelegate(itemClickedListener : (Cat) -> Unit) = adapterDelegateLayoutContainer(R.layout.item_cat) { name.setClickListener { itemClickedListener(item) } // no need for findViewById(). Name is imported as synthetic property from kotlinx.android.synthetic.main.item_cat bind { diffPayloads -> name.text = item.name } } ``` -------------------------------- ### Fallback AdapterDelegate: Handle Unknown View Types Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Demonstrates how to set up a fallback AdapterDelegate to handle view types that don't match any registered delegate. This prevents runtime exceptions and allows graceful handling of unexpected data types. The fallback delegate's isForViewType return value is ignored. ```java AdapterDelegate fallbackDelegate = ...; adapterDelegateManager.setFallbackDelegate( fallbackDelegate ); ``` -------------------------------- ### Managing Adapter Delegates with AdapterDelegatesManager (Java) Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt AdapterDelegatesManager facilitates the use of multiple AdapterDelegates in a RecyclerView by automatically assigning view types or allowing explicit ones, with fallback support for unknown types. It requires AdapterDelegates library and RecyclerView dependencies; inputs are lists of items like List, outputs are delegated ViewHolders for binding. Limitations include manual item count handling in the custom adapter. ```java // Manual delegate management AdapterDelegatesManager> manager = new AdapterDelegatesManager<>(); // Add delegates with automatic view type assignment manager.addDelegate(new CatAdapterDelegate(activity)); manager.addDelegate(new DogAdapterDelegate(activity)); // Add delegate with explicit view type manager.addDelegate(100, new AdvertisementAdapterDelegate(activity)); // Set fallback for unknown types manager.setFallbackDelegate(new UnknownAnimalDelegate(activity)); // Use in custom adapter public class CustomAdapter extends RecyclerView.Adapter { private AdapterDelegatesManager> delegatesManager; private List items; public CustomAdapter(AdapterDelegatesManager> manager) { this.delegatesManager = manager; } @Override public int getItemViewType(int position) { return delegatesManager.getItemViewType(items, position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return delegatesManager.onCreateViewHolder(parent, viewType); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { delegatesManager.onBindViewHolder(items, position, holder, null); } @Override public int getItemCount() { return items != null ? items.size() : 0; } } ``` -------------------------------- ### Define AdapterDelegate as fun in Kotlin Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Defines a top-level function AdapterDelegate for Cats. This approach allows the delegate to be garbage collected when not in use, making it more memory efficient than using a val. ```kotlin fun catAdapterDelegate() = adapterDelegate { ... bind { ... } } ``` -------------------------------- ### Implement fallback handler for unknown item types Source: https://context7.com/sockeqwe/adapterdelegates/llms.txt Creates a fallback adapter delegate to handle unrecognized item types gracefully in RecyclerView. Useful for preventing crashes when encountering unexpected data types. Depends on AbsFallbackAdapterDelegate base class and requires implementation of ViewHolder creation and binding logic. ```java public class ReptilesFallbackDelegate extends AbsFallbackAdapterDelegate> { private LayoutInflater inflater; public ReptilesFallbackDelegate(Activity activity) { inflater = activity.getLayoutInflater(); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent) { View view = inflater.inflate(R.layout.item_unknown_reptile, parent, false); return new ReptileFallbackViewHolder(view); } @Override public void onBindViewHolder(@NonNull List items, int position, @NonNull RecyclerView.ViewHolder holder, @Nullable List payloads) { ReptileFallbackViewHolder vh = (ReptileFallbackViewHolder) holder; DisplayableItem unknownItem = items.get(position); vh.message.setText("Unknown reptile type: " + unknownItem.getClass().getSimpleName()); vh.details.setText("Cannot display this item"); vh.itemView.setOnClickListener(v -> { Log.w("Fallback", "Unknown item clicked at position " + position); }); } class ReptileFallbackViewHolder extends RecyclerView.ViewHolder { public TextView message; public TextView details; public ReptileFallbackViewHolder(View itemView) { super(itemView); message = itemView.findViewById(R.id.message); details = itemView.findViewById(R.id.details); } } } ``` -------------------------------- ### Define AdapterDelegate as val in Kotlin Source: https://github.com/sockeqwe/adapterdelegates/blob/master/README.md Defines a top-level val AdapterDelegate for Cats. This approach creates a static field that remains in memory for the application's lifetime. It's less memory efficient than using a function. ```kotlin val catDelegate = adapterDelegate { ... bind { ... } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.