Gallery (Displaying String Array)

Gallery (Showing array of string)

/res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<TextView android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:text="Gallery Demo"
		android:id="@+id/txt" />
	<Gallery android:id="@+id/gallery" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:gravity="center_horizontal"
		android:spacing="100px" android:scrollbars="horizontal" />
</LinearLayout>

Activity file

package com.androidwork.gallerydemo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.widget.TextView;

public class GalleryDemoActivity extends Activity {
	/** Called when the activity is first created. */
	Gallery gallery;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		gallery = (Gallery) findViewById(R.id.gallery);
		// String array holding the values
		String[] text = new String[] { "Hello", "Hi", "Alloha", "Bonjour",
				"Hallo", "¡Hola" };
		// Array adapter to display our values in the gallery control
		ArrayAdapter<String> arr = new ArrayAdapter<String>(this,
				android.R.layout.simple_gallery_item, text);
		gallery.setAdapter(arr);

		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				TextView txt = (TextView) findViewById(R.id.txt);
				txt.setText(gallery.getItemAtPosition(arg2).toString());
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});
	}
}

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