Search code examples
androidlayoutscrollviewandroid-relativelayout

android which layout for elements side by side


I'm new on android programmation. I want to achieve a simple layout with elements side by side inside a scrollview. The idea is to process a single element per time with image and text, letting the layout choose when its the right time for the carriage return, in dependence of the screen resolution. I tried every type of layout, but no one seems to be suitable for my purpose. Particulary with Relative Layout elements are overlapped, instead what I need is an spatial append. Before to try a workaroud (for example adding more element in a row inside a linear layout) i would to know if exists a more natural solution.

layout
(source: youth-stories.com)

I create an example activity to try the solutions:

   public class MainActivity extends ActionBarActivity {

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

            final RelativeLayout container = (RelativeLayout)findViewById(R.id.container);

            for(int i=0; i < 100; i++)
            {
                final Button button = new Button(this);
                button.setText("sda"+i);
                button.setId(i);
                container.addView(button);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        container.removeView(button);
                    }
                });
            }

        }
    }

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="0dp"
    android:id="@+id/outer"
    android:tileMode="disabled" android:gravity="top">


    <ImageView android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/background"
        android:scaleType="centerCrop"/>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/scrollView" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/container"></RelativeLayout>
    </ScrollView>

</RelativeLayout>

Solution

  • From the above fig given, you can use GridView to draw UI as given. You can specify spacing between items also how many columns each row consists. For reference check developer doc.

    Check here for GridView example and doc