Mishel
Mishel

Reputation: 169

List of different types as argument

I need to pass 2 lists of different types (which depends of use case) from fragment to adapter constructor, in my one recyclerview.

So in BindViewHolder I should take that list of necessary type, get 1 item and set it to viewholder.

What can be the best way to insert "abstract" list type ? I try to do it with Object, but it seems to be wrong way.

Adapter:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

private List<Object> articles;

public MyAdapter(List<Object> articles, Context context) {
    this.articles = articles;
    this.context = context;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// ???
    Object article = getOneArticleFromArticles(articles, position);

//  here in in setText I only can get title from my concrete entity type 
    holder.title.setText(article.getTitle());
...

first entity:

public class Foo {
private String title;

public String getTitle() {
    return title;
  }
}

second entity:

public class Bar {
private String title;

public String getTitle() {
    return title;
}
  }

Usage

adapter = new MyAdapter(#response items from Foo#, getActivity());

adapter = new MyAdapter(#response items from Bar#, getActivity());

Upvotes: 0

Views: 56

Answers (1)

Szymon
Szymon

Reputation: 43023

Looking at the question and comments, you want something that will provide a common way to get the title through getTitle() but will also allow you to have other methods for each "implementation" class.

An interface is a simple way to do it. You can define getTitle() in the interface and make each class implement it.

You can then use this interface as a type for parameter passed to the adapter.

Upvotes: 1

Related Questions