Search code examples
androidbuttonscrollimageview

How to create 2 column layout dynamically in android?


MOCK UP

2-column layout

Overview

All are the ImageView with buttons with Scrolling

Requirement

I want to implement 2-Column fix layout for the image display.

And from the press the Button , it would be detect that image.

If only 1 image came then it display only one image in layout.


Solution

  • Try to use GridView.Look into this for your reference. For 2 column layout give android:numColumns = "2". Load the ImageView and Button dynamically using Adapter. For this,

    1.Create an xml which hold the GridView.

    <GridView
        android:id="@+id/gridFriends"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:numColumns="2"/>
    

    2.To define the contents of the GridView, create another XML layout which will hold the ImageView and the ImageButton.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mainContainer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
            <ImageView
                android:id="@+id/img"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:adjustViewBounds="true"
                android:scaleType="centerCrop"
                android:src="@null" />
    
            <Button
                android:id="@+id/btn"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom|center">
            <Button>
       </RelativeLayout>
    

    Create a customAdapter for populating the GridView dynamically.Look this for creating custom adapter.In that CustomAdapter getView() inflate the layout(in step 2)