AndroidEnthusiast
AndroidEnthusiast

Reputation: 6657

Creating a View with different types of adapters depending on the row

I am trying to replicate this Google Now card interface. I'm not worried about the feel of the cards but I'm more concerned with how the view is built.

Google Now Cards

I was thinking of using an adapter which returns different layouts corresponding to the row. But as you can see both views contain information which does not relate to one another.

Is it possible to have a ListView with different row adapters?

Or how could I achieve this using a custom view?

Upvotes: 3

Views: 4365

Answers (2)

KaHeL
KaHeL

Reputation: 4371

First you need to create a CustomAdapter for this:

public class CustomAdapter extends BaseAdapter {
    ArrayList<View> views;
    Context context;

    public CustomAdapter(Context context, ArrayList<View> views){
        this.views = views;
        this.context = context;
    }

    @Override
    public int getCount() {
        return views.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View rowView = views.get(i);
        /*set the views of the rowView here but take note use try catch since you can't be sure if the view will be present or not this is the part where I do not advice it to have different custom views per row but it's all yours to do your tricks*/

        return rowView;
    }
}

And to use it here's my sample method on create:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        ArrayList<View> views = new ArrayList<View>();

        CustomAdapter adapter = new CustomAdapter(MainActivity.this,views);
        ListView custom_list = (ListView)findViewById(R.id.list_custom);
        custom_list.setAdapter(adapter);

        LayoutInflater inflater = (LayoutInflater)   getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view1 = inflater.inflate(R.layout.view1, null);
        View view2 = inflater.inflate(R.layout.view2, null);

        views.add(view1);
        views.add(view2);
        adapter.notifyDataSetChanged();
}

Do your workaround if there's a need but basically this is just it. Inflate the views, pass it on your arrayList then set it on your listView.

Upvotes: 0

Dreagen
Dreagen

Reputation: 1743

You'll want to do this using a single adapter and inflating different views based on the position in the list. A good answer to this question is here:

Android ListView with different layouts for each row

Upvotes: 3

Related Questions