Wednesday 29 August 2012

Android Galary Container : Code Example

Galary:

  • Contains a horizontally scrolling list of View objects, also often used with image icons; the user can select an item to perform some action upon.
Let's take Simple Example which shows the Galary of  TextView that will be scrolled horizontally and you can select on of them. 

The Layout of this app is as follows : 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:text="Select Color"
  android:id="@+id/textView1"
  android:textAppearance="?android:attr/textAppearanceLarge"
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content"
  />
  
 <Gallery android:layout_width="fill_parent"
  android:layout_height="wrap_content"
   android:id="@+id/gallary01" 
   android:spacing="100px" 
  android:layout_gravity="center"/>
</LinearLayout>

The Java file can be as follows.

 
package com.container;

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

public class GalaryContainerDemoActivity extends Activity {
    /** Called when the activity is first created. */
 Gallery g;
 TextView tv;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        String [] colors= {"Red","Green","Blue","Pink","Gray"};
        g=(Gallery)findViewById(R.id.gallary01);
        tv=(TextView)findViewById(R.id.textView1);
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_gallery_item, colors);
        g.setAdapter(adapter);
        
        g.setOnItemClickListener(new OnItemClickListener() {

   public void onItemClick(AdapterView<?> myAdapter, View view, int myItemId,
     long myLang) {
    // TODO Auto-generated method stub
    
    String selectedItem=g.getItemAtPosition(myItemId).toString();
    tv.setText("You Selected: "+ selectedItem);
    Toast.makeText(getApplicationContext(), selectedItem, 2).show();
   }
  });
    }
}

When you first run your app that will shown as follows.

 You can scroll horizontally using touch.
 For example you select "Green" than following output will be displayed.

No comments:

Post a Comment