Pages

Thursday, April 12, 2012

[Andriod] Custom dialog with gridview

Task: To improve the user-experience, I 'd like to make a dialog contains options with icons and text, and manage them in grid rather than column of options.


key components: AlertDialog, LayoutInflater, GridView, Adapter


General Conception

step  1: Put custom view in the dialog - Dialog, LayoutInflater.
step  2: Manage your grid of options - GridView, Adapter.

Technical Conception

step  1: Use LayoutInflater to load the custom layout, which contains your GridView.
step  2: Use your own Adapter to manage your GridView.
step  3: Define the behavior when users choose one of the options.
step  4: Use AlertDialog.Builder to set the view to the dialog as custom layout.


Practical steps 

 File used in this tutorial:

1. customdialog.xml: That is what will be shown in your dialog, add a GridView here.
2. customcontent.xml: The format of every option in your grid, put an ImageView with any icon and a TextView under it.
note:  You can choose another arrangement you want, I put the text under a icon here
3. customIconGridActivity.java: Your main activity.
4. main.xml: put a button to launch the function
5. Icons your wish to show on your options, store them under res/drawable
    In this tutorial, I put three picture:cat.png, yao.png, and spider.png under res/drawable-mdpi

As a tutorial, I add all the object with Eclipse GUI and keep the default id such as imageView1, textView1, etc.
   


Code

customIconGridActivity.java
-------------------------------------

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.View.OnClickListener;
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;
/*
 *
step  1: Use LayoutInflater to load the custom layout, which contains your GridView.
step  2: Use your own Adapter to manage your GridView.
step  3: Define the behavior when users choose one of the options.
step  4: Use AlertDialog.Builder  to set the view to the dialog as custom layout.
 */
public class CustomIconGridActivity extends Activity {
    Context m_context = this;
    Dialog  m_dialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Button myButton = (Button) findViewById(R.id.button1);
        myButton.setOnClickListener(new OnClickListener(){

            public void onClick(View v) {
                // TODO Auto-generated method stub
                showDialog(0);
            }
      
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        //step 1:Load custom dialog layout
        LayoutInflater myInflater = LayoutInflater.from(m_context);
        View myView = myInflater.inflate(R.layout.customdialog, null);
      
      
        GridView gv = (GridView) myView.findViewById(R.id.gridView1);
        //step 2: Set self-defined ImageAdaper to our gridview
        gv.setAdapter(new ImageAdapter(m_context));
              
        //step 3: Set up the behavior when user touches an item in the grid
        gv.setOnItemClickListener(new GridView.OnItemClickListener(){

            public void onItemClick(AdapterView<?> parent, View v,int position, long id)
            {
              
                // TODO Auto-generated method stub
                Toast.makeText(v.getContext(), "Position is "+position, Toast.LENGTH_SHORT).show();
                //remove this statement if you want keep the dialog after user touched
                m_dialog.dismiss();
            }
          
        });
      
        //step 4: Set the custom view to the AlertDialog      
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("choose a context");
        builder.setView(myView);
      
        m_dialog = builder.create();
      
        return m_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 index

        public View getView(int position, View convertView, ViewGroup parent) {
            //ViewHolder is a self-defined class, and every instance is consisted of an icon and a text
            ViewHolder holder;
            if (convertView == null) {  // if it's not recycled,   

                convertView = mInflater.inflate(R.layout.customcontent, null);
                //convertView.setLayoutParams(new GridView.LayoutParams(90, 90));
                holder = new ViewHolder();
              
                //set any text and pic on the views, they will be replaced later
                holder.title = (TextView) convertView.findViewById(R.id.textView1);
                holder.icon = (ImageView )convertView.findViewById(R.id.imageView1);
              
                convertView.setTag(holder);
              
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.icon.setAdjustViewBounds(true);
            //holder.icon.setScaleType(ImageView.ScaleType.CENTER_CROP);   
            holder.icon.setPadding(8, 8, 8, 8);
            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.spider, R.drawable.yao,R.drawable.cat, 
                R.drawable.spider, R.drawable.yao,R.drawable.cat,
                R.drawable.yao
        };


        private String[] categoryContent = {   
                "spider0", "yao1", "cat2",
                "spider3", "yao4", "cat5",
                "yao6"

        };

    }
  
}



reference: http://iserveandroid.blogspot.com/2010/12/custom-gridview-in-dialog.html

No comments:

Post a Comment