在寫Android的底部菜單條的時候,如果用Button就特別難以調整,所以我覺得用GridView會使介面更容易調整和封裝。
一、基本使用布局設定:
<GridView android:id="@+id/gv_bottom_menu" android:layout_width="fill_parent" android:layout_height="@dimen/bottom_height" > </GridView>
GridView中每項的布局的設定:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="@dimen/bottom_height" > <ImageView android:id="@+id/item_image" android:layout_width="30dp" android:layout_height="30dp" android:layout_centerHorizontal="true" android:scaleType="centerInside" /> <TextView android:id="@+id/item_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/item_image" android:layout_centerHorizontal="true" android:textColor="@drawable/style_btn_text_color" /></RelativeLayout>
在程式中的使用:
ArrayList<HashMap<String, Object>> al = new ArrayList<HashMap<String, Object>>();for (int i = 0; i < img.length; i++) {HashMap<String, Object> map = new HashMap<String, Object>();map.put("itemImage", img[i]);//img[]是對應GridView中小布局中每個圖片的id數組map.put("itemText", text[i]);al.add(map);}inflater = LayoutInflater.from(context);inflater.inflate(R.layout.layout_bottom_bar_style, this, true);gv_bottom_menu = (GridView) findViewById(R.id.gv_bottom_menu);gv_bottom_menu.setNumColumns(num);gv_bottom_menu.setGravity(Gravity.CENTER);gv_bottom_menu.setVerticalSpacing(10);gv_bottom_menu.setHorizontalSpacing(10);SimpleAdapter adapter = new SimpleAdapter(context, al,R.layout.item_bottom_bar, new String[] { "itemImage","itemText" }, new int[] { R.id.item_image,R.id.item_text });gv_bottom_menu.setAdapter(adapter);
二、改變點擊GridView後,其中Item的內容
添加屬性
android:listSelector="@drawable/style_btn_1"
<GridView android:id="@+id/gv_bottom_menu" android:layout_width="fill_parent" android:layout_height="@dimen/bottom_height" android:descendantFocusability="afterDescendants" android:gravity="center" > </GridView>
三、改變點擊的GridView的每一塊的背景
添加屬性
android:descendantFocusability="afterDescendants"
<GridView android:id="@+id/gv_bottom_menu" android:layout_width="fill_parent" android:layout_height="@dimen/bottom_height" android:descendantFocusability="afterDescendants" android:gravity="center" android:listSelector="@drawable/style_btn_1" > </GridView>
drawable檔案夾中的點擊改變
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/tab2" android:state_pressed="true"></item> <item android:drawable="@drawable/tab2" android:state_focused="true"></item> <item android:drawable="@drawable/bg_tab"></item></selector>