GridView (Displaying String Array)

GridView (Display String Array)

/res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@+id/gridview" android:layout_width="fill_parent"
	android:layout_height="fill_parent" android:columnWidth="90dp"
	android:numColumns="auto_fit" android:verticalSpacing="10dp"
	android:horizontalSpacing="10dp" android:stretchMode="columnWidth"
	android:gravity="center" />

Activity File

package com.androidwork.gridviewdemo;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;

public class GridViewDemoActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		GridView gridview = (GridView) findViewById(R.id.gridview);
		final String[] items = new String[] { "Item1", "Item2", "Item3",
				"Item4", "Item5", "Item6", "Item7", "Item8" };

		ArrayAdapter<String> ad = new ArrayAdapter<String>(
				getApplicationContext(), android.R.layout.simple_list_item_1,
				items);
		gridview.setBackgroundColor(Color.GRAY);
		gridview.setNumColumns(2);
		gridview.setGravity(Gravity.CENTER);
		gridview.setAdapter(ad);

		gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Toast.makeText(getApplicationContext(), "" + arg2,
						Toast.LENGTH_SHORT).show();
			}
		});

	}
}

Output

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s