Search code examples
androidlayout-inflaterhorizontalscrollview

How to make a horizontal scrollable view?


I have a horizontal scroll view containing a linear layout. Something like this:

<HorizontalScrollView
    android:fillViewport="true"
    android:id="@+id/product_hsv"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:measureAllChildren="false"
    android:scrollbars="none">

    <LinearLayout
        android:id="@+id/product_container_layout"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="horizontal" />
</HorizontalScrollView>

What I want to do is to add n number of the same layout to display product collection in a Horizontal scroll view.

The picture below will give you an idea of what I have done so far.

Expected output

For this, I have added product collection view to R.id.product_container_layout.

String[] productCollectionArr = new String[]{"Shirt", "Jewellary", "Moto X Play", "Ellis Flat"};

for (int i = 0; i < productCollectionArr.length; i++) {
    LinearLayout parentLayout = (LinearLayout) findViewById(R.id.product_container_layout);
    View child = getLayoutInflater().inflate(R.layout.item_product, null);//child.xml
    parentLayout.addView(child);
}

for (int i = 0; i < productCollectionArr.length; i++) {
    LinearLayout eachProductLayout = (LinearLayout) findViewById(R.id.product_container_layout);
    ((TextView) eachProductLayout.findViewById(R.id.product_name_tv)).setText(productCollectionArr[i]);
}

But the problem is passing values. Since each view added to product_container_layout has the same ids. Therefore only first element gets the value from the product collection array.

What I can do is generate view id for each view and its element and map these ids to certain name so that I could access them by id.

Is this the correct methodology or should I do something else?.


Solution

  • So, you need to populate your view before adding to container or save links to all items. It will looks like this:

        LinearLayout parentLayout=(LinearLayout)findViewById(R.id.linearLayout1);
    for (int i = 0; i < items.size(); i ++) {
        View child = getLayoutInflater().inflate(R.layout.item_grid, null);//child.xml
    ((TextView) child.findViewById(R.id.name)).setText(items.get(i).getName(); // where R.id.name is a textView in your child.xml layout.
        parentLayout.addView(child);
    }
    

    after all, you can access to your elements by index, if you want to change it:

    parentLayout.getChildAt(index)
    

    But if you have a lot of items, it's not good idea. In this case you will not recycle your views and will consume a lot of memory. I suggest to use recyclerview from support library.