首页 > 解决方案 > 将 Xamarin 表单网格布局转换为 Xamarin Android

问题描述

假设我在 Xamarin Forms 项目的 .XAML 文件中有以下网格:

<Grid ColumnSpacing="12">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
</Grid>

我如何将此 XAML 标记转换为 Android XML?我已经阅读了GridLayoutTableLayout视图的文档,但我不确定我是否完全理解它们之间的区别,因此不确定哪个最适合这种情况。

另外,我有一个硬性要求,即我必须针对 Android API 级别 19。我之所以提到这一点,是因为上述文档中似乎有一些项目表明某些功能是在 API 级别 21 或 22 中添加的。

标签: androidxamarinxamarin.formsxamarin.android

解决方案


TableLayout 扩展LinearLayout,不需要指定声明包含多少行或列,通过添加TableRow/其他组件来控制表格的行数和列数,它不能跨越行和列。它不灵活

Android 4.0后添加的GridLayout,可以将整个容器划分为行*列的网格,可以设置一个组件跨越多少列或多少行

所以GridLayout更好用。

因为你的 xaml 没有内容,如果你使用 gridlayu ,你可以这样写:

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent" android:layout_height="match_parent"
  android:rowCount="3"
  android:columnCount="4"
  android:id="@+id/root">

  //content components
  ...
</GridLayout>

leftmargin,rightMargin和 item 的其他属性可以用来设置 item 的水平和垂直间距


推荐阅读