Search code examples
androidandroid-linearlayouthorizontalscrollview

Need to display two items at a time within a horizontal scroll view


I am trying to display two views within a horizontal scroll as shown in the picture below. I am wondering the possible ways to achieve this because the output that I have achieved is far from the requirement as we can see in the screen grabs below:-

Required Output

Here is a part of my layout which describes the view that i have implemented:-

  <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/imageGallery"
            android:layout_gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="3"/>

    </HorizontalScrollView>

To the above view i then created a linear layout with vertical orientation and added to it an imageview, and 3 text view as shown in the below code snippet:-

     @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private View getVerticalLinearLayout(Integer image){
        LinearLayout verticalLayout = new LinearLayout(getContext());
        verticalLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT,2.0f));
        verticalLayout.setOrientation(LinearLayout.VERTICAL);
        verticalLayout.setBackground(getResources().getDrawable(R.drawable.layout_border));
        verticalLayout.addView(scaleImage((ImageView) getImageView(image)));
        verticalLayout.addView(getTextView("Book Name",14,"#444444"));
        verticalLayout.addView(getTextView("Author Name",12,"#444444"));
        verticalLayout.addView(getTextView("Lender Name",12,"444444"));
        return verticalLayout;

    }

However what I have managed to achieve can be seen in the image below enter image description here


Solution

  • You can design your book views as individual layout file. You can then instantiate it using the LayoutInflater and populate it with your data and then finally add them individually to your imageGallery layout.

    To make exactly two views appear at a time on the screen you have to know the screen width. This is possible via DisplayMetrics or you can call getWidth() on a view that covers the screen fully horizontally. Once you get that width the bookView layouts that you will be adding to your horizontal scroll view need to have their width set to screenWidth/2.