注:网格布局通常在recyclerview的java中运用

一、网格布局的常见属性

  1. 1.android:columnCount 设置水平显示还是垂直显示<br /> 2.android:columnCount 设置行的显示个数<br /> 3.android:rowCount 设置列的显示个数

子控件属性

  1. 1.android:layout_column 显示在第几列<br /> 2.android:layout_columnSpan 横向跨几列<br /> 3.android:layout_columnWeight 横向剩余空间分配方式<br /> 4.android:layout_gravity 在网格中的显示位置<br /> 5.android:layout_row 显示在第几行<br /> 6.android:layout_rowSpan 横向跨几行<br /> 7.android:layout_rowWeight 纵向剩余空间分配方式

二、网格布局的实现

  1. 1.布局activity_main.xml文件
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:layout_width="match_parent"
  6. android:layout_height="match_parent"
  7. android:columnCount="3"
  8. android:orientation="horizontal">
  9. <Button
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:text="第1个"
  13. android:layout_columnSpan="2"
  14. android:layout_gravity="fill"
  15. />
  16. <Button
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:text="第2个"
  20. android:layout_row="1"
  21. android:layout_column="2"
  22. />
  23. <Button
  24. android:layout_width="wrap_content"
  25. android:layout_height="wrap_content"
  26. android:text="第3个"
  27. />
  28. <Button
  29. android:layout_width="wrap_content"
  30. android:layout_height="wrap_content"
  31. android:text="第4个"
  32. android:layout_columnWeight="1"
  33. />
  34. <Button
  35. android:layout_width="wrap_content"
  36. android:layout_height="wrap_content"
  37. android:text="第5个"
  38. />
  39. </GridLayout>
  1. 2.效果图:<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/1574587/1622044316543-78c2234f-e495-4118-9d77-08dfa3d0515a.png#clientId=u16afdabf-be09-4&from=paste&height=522&id=u565b0974&margin=%5Bobject%20Object%5D&name=image.png&originHeight=522&originWidth=922&originalType=binary&size=76173&status=done&style=none&taskId=ue1519494-f07e-4651-8c7e-0ba61fab0e0&width=922)