在写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>