先看效果圖: 如下
下面是代碼部分:
1. 在main.xml中添加GridView
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:background="@drawable/background"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <GridView
- android:id="@+id/grid_view"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:numColumns="5"
- android:horizontalSpacing="10dp"
- android:verticalSpacing="10dp">
- </GridView>
- </RelativeLayout>
2.注意:菜單欄中的每一子項都需要一個布局文件
如上圖 是一個垂直布局的LinearLayout
menu_item.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- <ImageView
- android:id="@+id/item_iamge"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"
- />
- <TextView
- android:id="@+id/item_text"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_gravity="center_horizontal"/>
- </LinearLayout>
3.主要代碼部分 MainActivity.java
- package com.yin.bottom_menu;
- import java.util.ArrayList;
- import java.util.HashMap;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.GridView;
- import android.widget.SimpleAdapter;
- public class MainActivity extends Activity {
- //圖片資源
- private static int[] images = {
- R.drawable.menu_add_new,
- R.drawable.menu_delete,
- R.drawable.menu_exit,
- R.drawable.menu_search,
- R.drawable.menu__list
- };
- //菜單欄中的文字顯示
- private static String[] menu_texts = {
- "增加","刪除","退出","查找","菜單"
- };
-
- private ArrayList<HashMap<String,Object>> menu_data ;
-
- private GridView grid_view;
-
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- init_menu();
- }
- //初始化底部菜單欄
- private void init_menu(){
- grid_view = (GridView) findViewById(R.id.grid_view);
-
- add_menu_data();
-
- //向菜單欄中的控件添加適配其
- SimpleAdapter adapter = new SimpleAdapter(this, menu_data, R.layout.menu_item,
- new String[]{"menu_image","menu_text"}, new int[]{R.id.item_iamge,R.id.item_text});
-
- grid_view.setAdapter(adapter);
- }
- //添加菜單欄中顯示的數據
- private void add_menu_data(){
- menu_data = new ArrayList<HashMap<String,Object>>();
- for(int i=0;i<images.length;i++){
- HashMap<String,Object> map = new HashMap<String, Object>();
- map.put("menu_image", images[i]);
- map.put("menu_text", menu_texts[i]);
- menu_data.add(map);
- }
- }
- }