研究了一下Android的GridView,但是默认的GridView只支持垂直滚动,不支持水平滚动,有时我们为了实现表格效果,想达到水平和垂直均有滚动条,可以利用下面方法实现)。
1)main.xml -- 布局文件
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:alwaysDrawnWithCache="true"
android:orientation="vertical"
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="horizontal|vertical" >
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent" >
<GridView
android:id="@+id/data_gridview"
android:layout_width="1395dip" <!--表格需要45列,每列31dip,所以总的宽度是1395dip-->
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#ff0000"
android:columnWidth="31dip" <!--每列的宽度-->
android:gravity="center"
android:numColumns="45" <!-- 注意这里,指定gridview有45列,每列的宽度是31个dip-->
android:scrollbarAlwaysDrawHorizontalTrack="true"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:scrollbars="horizontal|vertical"
android:horizontalSpacing="1dip" <!-- 这里和下面的1dip是为了显示表格的格子边框线,做成像表格的效果-->
android:verticalSpacing="1dip" />
</FrameLayout>
</HorizontalScrollView>
2) 每个gridcell对应的layout文件 --
imagecell.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView android:id="@+id/CellImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" >
</ImageView>
</RelativeLayout>
3)Activity的代码 -- 这里为了提高性能,实现了重用View的机制
package com.xxxx.ui
import xxxx.xxxx
public class GridViewTestActivity extends Activity {
private int disp_rows = 20; //显示多少行
private final static int COLUMN_CNT = 45; //显示多少列,这个要和layout文件里面对应起来
private GridView dataGridView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataGridView = (GridView) findViewById(R.id.data_gridview);
dataGridView.setNumColumns(COLUMN_CNT);//一共45列
dataGridView.setAdapter(new CellAdapter(getApplicationContext()));
dataGridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(GridViewTestActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
} //end onCreate
class CellAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater mInflater;