Showing posts with label gridview. Show all posts

Wednesday, December 11, 2013

GridView Auto resized images in Android Example

2 comments :
Hi,

   This is an Example for Gridview with auto resized images with Textview in Android

1. First create a xml layout with Gridview and setting a stretch mode to stretch column width and set spacing to 0 and set the no of columns to 0 This is an Main Activity layout

activity_main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/FrameLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <GridView
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:gravity="center"
        android:stretchMode="columnWidth"
        android:numColumns="auto_fit" >
    </GridView>

</FrameLayout>

2. Create an another layout for grid item textview using squareimageview class and set the scale type to center crop. Now xml name is grid_item.xml.

grid_item.xml:

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.socialnetwork.squareimageview
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        />
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"
        />
</FrameLayout>

3.Now create the custom class extends ImageView calling it in squareimageview.java


squareimageview.java:


package com.example.socialnetwork;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class squareimageview extends ImageView
{


public squareimageview(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public squareimageview(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}


public squareimageview(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub

}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(),getMeasuredWidth());

}

}


4.Create a adapter to handle the list,the adapter is defined in an inner class (no need to create a new class file). Let's call it MyAdapter and make it extend the BaseAdapter class.

MainActivity.java:

package com.example.socialnetwork;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {

GridView gd;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gd=(GridView)findViewById(R.id.gridView1);
gd.setAdapter(new MyAdapter(this));

}

public class MyAdapter extends BaseAdapter
{

private List<Item> items=new ArrayList<Item>();
private LayoutInflater inflator;

public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
inflator=LayoutInflater.from(context);
items.add(new Item("Facebook",R.drawable.fb));
items.add(new Item("Twitter",R.drawable.twitter));
items.add(new Item("Linkedin",R.drawable.linkedin));
items.add(new Item("Google+",R.drawable.google));
items.add(new Item("Youtube",R.drawable.rss));
items.add(new Item("Myspace", R.drawable.fb));

}

@Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return items.get(position).drawableId;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View v=convertView;
ImageView img1;
TextView txt1;
if(v==null)
{
v=inflator.inflate(R.layout.grid_item,parent,false);
v.setTag(R.id.picture,v.findViewById(R.id.picture));
v.setTag(R.id.text,findViewById(R.id.text));

}

   img1=(ImageView)v.findViewById(R.id.picture);
   txt1=(TextView)v.findViewById(R.id.text);
 
   Item item=(Item)getItem(position);
 
   img1.setImageResource(item.drawableId);
   txt1.setText(item.name);
       
return v;
}

}

private class Item
{
final String name;
final int drawableId;

Item(String name,int drawableId)
{
  this.name=name;
  this.drawableId=drawableId;

}
}


}

5.Run the Application and Here the output is like this


                 



Friday, November 22, 2013

Custom Dialog using Gridview in Android

6 comments :
Hi,

This is an example for Creating custom dialog using Gridview in Android

using this we can choose an picture or "choose an categories"

1 - Dialog 

onCreateDialog(int id) --> Is the function which will be called by framework,when an activity has implmented and showDialog(int id ) is called on activity's instance.
So we go ahead and implement this onCreateDialog(int id) function.

2 - Layouts

The view can be split into two parts.

- LinearLayout vertical orientation holding two elements.

- RelativeLayout - Title and Exit icons at the right extreme.
- GridView - Display 3x3 icons& text as a view.


main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="183dp"
        android:text="Button" />


</RelativeLayout>


3 - Creating Dialog

Lets use the AlertDialog and set the categoryDialog.xml layout to its setView() api to show the content. what we are exepecting.

Use inflater to create a view by inflating R.layout.category

category.xml:




<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/layout_root"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              >
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="3dip" >
    <ImageView android:id="@+id/close"
    android:layout_width="30dip" 
    android:layout_height="30dip" 
               android:layout_alignParentRight="true"
               android:layout_marginRight="3dp"
               android:src="@drawable/close"
               />
    <TextView android:id="@+id/text1"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerHorizontal="true"
              android:layout_alignParentLeft="true"
              android:layout_marginLeft="3dp"
              android:textColor="#FFF"
              android:textSize="20dip"
              android:text="Choose Categories"/>
</RelativeLayout>
              
 <GridView 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="3"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"/>
</LinearLayout>

4.We need to implement a BaseAdapter and when the adapter instance is set to GridView , GridView queries for how many elements and what are their each view to display in the Grid.

- Each view in the grid is Icon (image) and a text corresponding to the category. So we need to create one more layout xml file to hold these content.

Custom.xml:


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="10dp"
              >
    <ImageView android:id="@+id/image"
      android:layout_width="50dip" 
    android:layout_height="50dip" 
    android:layout_alignParentRight="true"
               android:layout_marginRight="3dp"/>
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_centerHorizontal="true"
              android:layout_alignParentLeft="true"
              android:layout_marginLeft="3dp"
              android:textColor="#FFF"/>
              
</LinearLayout>

5.  Create a view inflating this layout xml file and set the LayoutParams for each cell size as 90x90. 

    convertView=mInflator.inflate(R.layout.category,null);
    convertView.setLayoutParams(new GridView.LayoutParams(90,90)));

Note: Since this a view which will be set in GridView as one element of Grid, the layout params must be of type GridView.LayoutParams. This is very important otherwise, the programs will crash in run-time.


6.  create a class called MainActivity.class

MainActivity.java:


package com.example.customdialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class MainActivity extends Activity {
 public final int CATEGORY_ID =0;
 private Context mContext;
 Dialog dialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         mContext = getApplicationContext();
        setContentView(R.layout.main);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View v)
            {
                    showDialog(CATEGORY_ID);
            }
        });
    }
    protected Dialog onCreateDialog(int id) {
     
        switch(id) {

        case CATEGORY_ID:
     
         AlertDialog.Builder builder;
            Context mContext = this;
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
            View layout = inflater.inflate(R.layout.activity_main,(ViewGroup) findViewById(R.id.layout_root));
            GridView gridview = (GridView)layout.findViewById(R.id.gridview);
            gridview.setAdapter(new ImageAdapter(this));
         
           gridview.setOnItemClickListener(new OnItemClickListener()
            {
             
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(arg1.getContext(), "Position is "+arg2, 3000).show();
}
            });
         
            ImageView close = (ImageView) layout.findViewById(R.id.close);
            close.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v){
              dialog.dismiss();
            }
            });
         
            builder = new AlertDialog.Builder(mContext);
            builder.setView(layout);
            dialog = builder.create();
            break;
        default:
            dialog = null;
        }
        return dialog;
    }
 
  public class ImageAdapter extends BaseAdapter {
        private Context mContext;
        private LayoutInflater mInflater;
        public ImageAdapter(Context c) {
         mInflater = LayoutInflater.from(c);
            mContext = c;
        }
        public int getCount() {
            return mThumbIds.length;
        }
        public Object getItem(int position) {
            return null;
        }
        public long getItemId(int position) {
            return 0;
        }
        // create a new ImageView for each item referenced by the
        public View getView(int position, View convertView, ViewGroup parent) {
         ViewHolder holder;
            if (convertView == null) {  // if it's not recycled,
                 convertView = mInflater.inflate(R.layout.custom, null);
               convertView.setLayoutParams(new GridView.LayoutParams(100,100));
              holder = new ViewHolder();
                 holder.title = (TextView) convertView.findViewById(R.id.categoryText);
                 holder.icon = (ImageView )convertView.findViewById(R.id.categoryimage);
                 convertView.setTag(holder);
             } else {
                 holder = (ViewHolder) convertView.getTag();
             }
    holder.icon.setAdjustViewBounds(true);
    holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);
    holder.icon.setPadding(5, 5, 5, 5);
    holder.title.setText(categoryContent[position]);
    holder.icon.setImageResource(mThumbIds[position]);
    return convertView;
        }
        class ViewHolder {
            TextView title;
            ImageView icon;
        }
        // references to our images
        private Integer[] mThumbIds = {
                R.drawable.img5, R.drawable.img1,R.drawable.img2,
                R.drawable.img3,R.drawable.img4, R.drawable.img5,
                R.drawable.img6, R.drawable.img3,R.drawable.img1
                };

     }
    private String[] categoryContent = {
          "Pubs", "Restuarants","shopping",
          "theatre","train", "taxi",
          "gas", "police","hospital"
          };


}

7.Here the output like this






I think this is so usefull to everyone