我们将通过两个例子学习GridView。Grid和Table有一点点类似。我们将在例子中逐步描绘如何编写一个Grid的Activity
例子一:继承ArrayAdapter作为自定义adapter
1、编写Android XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/selection4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<GridView android:id="@+id/grid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:verticalSpacing="35px" <!-- grid元素之间的竖直间隔 -->
android:horizontalSpacing="5px" <!--grid元素之间的水平间隔 -->
android:numColumns="auto_fit" <!--表示有多少列,如果设置为auto_fit,将根据columnWidth和Spacing来自动计算 -->
android:columnWidth="100px" <!-- 一般建议采用有像素密度无关的dip或者dp来表示-->
android:stretchMode="columnWidth" <!--如何填满空余的位置,模拟器采用WVGA800*480,每排4列,有4*100+5*3=415,还余65px的空间,如果是columnWidth,则这剩余的65将分摊给4列,每列增加16/17px。如果采用SpacingWidth,则分摊给3个间隔空隙 -->
android:gravity="center" />
</LinearLayout>
2、编写代码。和其他selected widget,我们之前学习的ListView和Spinner的方式,通过setAdapter()来提供数据和子View显示风格,通过触发setOnItemSelectedListener()注册选择listner。在这里处理选择之外,我们增加一个Click的触发,可以比较一下此两的差异。此次我们不再使用Android自带的格式,而设置我们自己的UI风格。
public class Chapter7Test4 extends Activity implements OnItemSelectedListener,OnItemClickListener{
private TextView selection = null;
private String[] items={"lorem", "ipsum", "dolor", "sit", "amet", "hello", "