I am trying to dynamically add image buttons on the click of a button. When the number of image button exceeds the screen width, I should be able to horizontally scroll. I tried to implement Jess-Ander's TwoWayGridView but with no success. I am a beginner. So please bear with me if the mistake is too elementary.
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="Button" />
<com.jess.ui.TwoWayGridView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#E8E8E8"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:cacheColorHint="#E8E8E8"
app:columnWidth="80dp"
app:rowHeight="80dp"
app:numColumns="auto_fit"
app:numRows="2"
app:verticalSpacing="16dp"
app:horizontalSpacing="16dp"
app:stretchMode="spacingWidthUniform"
app:scrollDirectionPortrait="vertical"
app:scrollDirectionLandscape="horizontal"
app:gravity="center">
<LinearLayout
android:id="@+id/linearLayout1"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.jess.ui.TwoWayGridView>
</LinearLayout>
and here's the code:
package com.example.dynamic;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends Activity {
LinearLayout linearLayout1;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
}
public void onClick(View v){
ImageView image = new ImageView(MainActivity.this);
image.setBackgroundResource(R.drawable.ic_launcher);
linearLayout1.addView(image);
}
}
If you are having problems getting the spacing correct using the values in xml, you could try looking at the following tutorial:
http://spragucm.wordpress.com/2013/11/17/android-horizontal-and-vertical-gridview-tutorial/
I specifically wrote it because the two-way-gridview items wouldn't space evenly and they wouldn't fill the row/column. The example code in my tutorial lets you set column and row number and everything else is done for you so that the child fills a row/column with some padding between items.
The example code demonstrates how to use the two-way-gridview in either orientation.
As for setting the onClickListener...you will need to setOnItemClickListener() on the gridview.