Create Icon with Text Using GridView and Layout Inflater

By courtesy of mytelcoit.com
How to create Icon With text like home screen, here is my example screen:

null

To do something like this we need to use GridView and make The Icon with text using the XML layout and then using LayoutInflater to read the XML and put it into the Adapter. Lets begin with the icon.xml(we put it into /res/layout/) that will be the view to show ImageView and Text together.

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget44"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_x="201px"
android:layout_y="165px"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/icon_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageView>
<TextView
android:id="@+id/icon_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:gravity="center_horizontal"
android:textColorHighlight="#656565">
</TextView>
</LinearLayout>

Here we put the ImageView and TextView into Linear Layout. In line 7 and 8 we define how big is our icon with layout_x and layout_y. Thats all, this icon.xml file next we will use in the Adapter to fill in our GridView.

Lets go to our GridView XML. I name it main_switch.xml, this locate in /res/layout/.

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

In this XML file we define the main layout of our screen, and how will be the grid will be display. This will be load to our main Activity.

Lets go to our Activity Class

public class MainSwitch extends Activity{
	GridView grid_main;
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_switch);

		grid_main = (GridView)findViewById(R.id.GridView01);
		grid_main.setAdapter(new ImageAdapter(this));
	}
	public class ImageAdapter extends BaseAdapter{
		Context mContext;
		public static final int ACTIVITY_CREATE = 10;
		public ImageAdapter(Context c){
			mContext = c;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 5;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v;
			if(convertView==null){
				LayoutInflater li = getLayoutInflater();
				v = li.inflate(R.layout.icon, null);
				TextView tv = (TextView)v.findViewById(R.id.icon_text);
				tv.setText("Profile "+position);
				ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
				iv.setImageResource(R.drawable.icon);

			}
			else
			{
				v = convertView;
			}
			return v;
		}
	}
}

Line 4 – line 10 : we overide onCreate() from the Activity class, here we setContentView() to main_switch.xml, get the GridView and then fill it with the ImageAdapter class that extend from BaseAdapter.

line 24-41 : we define the view that will display on the grid, we use LayoutInflater to get view from icon.xml file that we already define before. We also can manipulate both ImageView and TextView with what parameter that we want to set, for example we can set the text or change the ImageView Resource, etc.

line 18-21 : we set how many icon we want to display.

This is another source of way to load image from the drawable

public class ImageAdapter extends BaseAdapter {
private Context mContext;

public ImageAdapter(Context 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 Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it’s not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}

imageView.setImageResource(mThumbIds[position]);
return imageView;
}

// references to our images
private Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
}

About these ads

7 comments on “Create Icon with Text Using GridView and Layout Inflater

  1. Hi…
    When i use OnItemClickListener() on the Gridview it is fine by using position or Id. But i need the text of the selected/clicked item on the gridview.
    EX: In the above screen shot when i click first icon.. I need the text “Profile 0″.
    Is it possible to get the Text?
    Please respond…..

    • Hi, regarding to your question, I think it is possible. you just change this,

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
      // TODO Auto-generated method stub
      View v;
      if(convertView==null){
      LayoutInflater li = getLayoutInflater();
      v = li.inflate(R.layout.icon, null);
      TextView tv = (TextView)v.findViewById(R.id.icon_text);
      tv.setText(“Profile “+position);
      ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
      iv.setImageResource(R.drawable.icon);
      iv.setOnClickListener(new Button.OnClickListener()
      {
      public void onClick(View v)
      {
      Toast.makeText(getApplicationContext(),”your text” + tv.getText(),
      Toast.LENGTH_LONG).show();

      }
      }
      });

      }
      ………………..
      I didnot test the code, but I think it will be ok.
      For me, to know which button is click it use the Id instead.

      ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
      iv.setImageResource(R.drawable.icon);
      iv.setId(iconID[position]);

      iconID is an array to hold icon number based on the position the Gridview generate…

      This is from my current project I take from.

      final ImageView iv = (ImageView)v.findViewById(R.id.icon_image);
      iv.setImageResource(imageLocation[position]);
      //iv.setImageResource(R.drawable.icon);
      iv.setId(iconID[position]);
      iv.setOnClickListener(new Button.OnClickListener()
      {

      public void onClick(View v)
      {
      try{
      String id = Integer.toString(iv.getId());

      if(Integer.parseInt(id) == 11)
      {
      Toast.makeText(getApplicationContext(),”YOU should not link to MainAd”,
      Toast.LENGTH_LONG).show();
      showDialog(DIALOG_MULTIPLE_CHOICE);
      }
      else {
      Intent intent = new Intent(AdmailSeason4ep2.this, MainAds.class);

      intent.putExtra(“iconNumber”, id);
      intent.putExtra(“userLat”,latitude);
      intent.putExtra(“userLon”, longitude);
      startActivity(intent);

      }

      }
      catch (Exception e) {

      }

      I hope it helps.

      • Hi Thnx for immidiate reply…
        I am using gridview.setOnItemClicklistner() to know the position of clicked item on Gridview. lly I need the text of clicked item not from the Adapter Class.

  2. Hi Thnx for immidiate reply…
    I am using gridview.setOnItemClicklistner() to know the position of clicked item on Gridview. lly I need the text of clicked item not from the Adapter Class.

  3. i did same as wat u said but in my grid layout i have 10 image with text.problem i m getting is after certain no of images like say after4th image i m gettng repetaiton of 1st image whereas below text remains same.(text of 5th image only).can u plzzz help me..

    • well, it was long ago. And I do remember I did face similar problem as you mentioned, if you could send me sample code, Maybe I could figured out. But don’t get your hope’s up, I don’t do android for too long. .. but for a quick notice, you can delete all your images, and put them there again. and the R. will regenerate it. It might solve. Last time I load image in the folder images, and stored its location in the sqllite, so I just load all my array based on the table. correct me if you found other solution already.

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