@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView menuGrid = (GridView) findViewById(R.id.menu);
menuGrid.setAdapter(new MenuAdapter(this));
menuGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v,
int position, long id) {
Toast.makeText(MainActivity.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
public class MenuAdapter extends BaseAdapter {
private Context context;
private String[] labels;
private int[] images = { R.drawable.menu_1, R.drawable.menu_2,
R.drawable.menu_3, R.drawable.menu_4 };
public MenuAdapter(Context context) {
this.context = context;
this.labels = context.getResources().getStringArray(R.array.menu_items);
}
@Override
public int getCount() {
return this.labels.length;
}
@Override
public Object getItem(int arg0) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) convertView;
if (textView == null) {
textView = (TextView) View.inflate(context, R.layout.menu_item,
null);
}
textView.setText(this.labels[position]);
textView.setCompoundDrawablesWithIntrinsicBounds(0, images[position],
0, 0);
return textView;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"Menu (Note that we use compound view (icon/text))
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
tools:context=".MainActivity" >
<include
android:layout_
android:layout_
layout="@layout/menu" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>MenuItem
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/menu"
android:layout_
android:layout_
android:layout_marginLeft="25dp"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:verticalSpacing="20dp" />
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/menuItem"
android:layout_
android:layout_
android:layout_gravity="center_horizontal"
android:drawableTop="@drawable/icon"
android:gravity="center_horizontal"
android:text="@string/common_label"
android:textColor="@color/menu_item" />
<string-array name="menu_items">
<item>Menu 1</item>
<item>Menu 2</item>
<item>Menu 3</item>
<item>Menu 4</item>
</string-array>