如何使用GridView这样创建表

时间:2012-09-13 12:17:34

标签: android

如何使用GridView创建表格如下:

example

我的意思是:

1st column - 2 rows;
2nd column - 1 row;
3rd column - 2 rows;
.... and so on 

1 个答案:

答案 0 :(得分:1)

您可以为gridview创建自定义适配器。

假设网格中的每个单元格都包含一个按钮,那么您需要一些列表

ArrayList<Button> listOfButtons = new ArrayList<Button>();

您的GridView将有7列,您需要在布局xml文件中指定

android:numColumns="5"

您的适配器类将检查列表并查看正在实例化的单元格。如果它是正确的单元格,则修改它。

public class MyAdapter extends BaseAdapter {

private Context context;

public MyAdapter(Context context) {
    this.context = context;
}

public int getCount() {
    return listOfButtons.size();
}

@Override
public boolean areAllItemsEnabled() {
    return true;
}

public boolean isEnabled(int position) {
    return true;
    // return true for clickable, false for not
}

public Button getItem(int position) {
    return listOfButtons.get(position);
}

public long getItemId(int position) {
    return listOfButtons.get(position).getId();
}

@Override
public int getViewTypeCount() {
    return 1;
}

public View getView(int position, View convertView, ViewGroup parent) {
        Button b;

        //Here is where you check to see if it's the correct cell
        //You can use the methods declared above to check
        //say i wanted every even item to be 1 cell

        if (position % 2 = 0)
            b.setHeight(100);//however high two columns are

        /*you'd also need to make the other button that's 
         * being overlapped invisible. This requires that 
         * you know what position it's going to be in. 
         * Using the same eample with 7 columns, 
         * position 8, 10, 12 and 14 will be overlapped so 
         * you can do something like*/
        if (position == 8 || position == 10 || 
            position ==12 || position ==14)
        {
            b.setVisibility(View.GONE);
            return b;
        }
        if (convertView == null) {
            b.setPadding(10, 10, 10, 10);
        } else {
            b = (Button) convertView;
        }

        //Set properties of each
        return b;
    }

}

希望这有帮助

相关问题