Android 和视图大小

Android and View size

我只想知道是否每次都需要将视图的大小(宽度 or/and 高度)设置为其父级大小(例如宽度 = 0.5 * parent_size)的函数,我必须创建一个自定义视图并覆盖 onMeasure() 或者有没有办法使用 XML 来实现? 提前致谢!

编辑:

我想要实现的是:放置一个左对齐的视图,宽度等于父宽度的 1/10,高度等于父高度的 1/5。其他观点以此类推。

I have to create a custom View and override onMeasure() or is there a way to do it using XML?

使用 XML 布局文件无法实现您的目标。

您必须动态管理此视图。您的第二种方法是正确的方法。 您需要创建动态视图并根据您的功能制作 onMeasure() 方法。

您可以使用 LinearLayout 作为容器,例如 android:layout 权重属性。您可以在这里阅读更多内容:developer.android.com/guide/topics/ui/layout/linear.html#Weight

因此,如果您只想添加一个元素,可以添加权重为 1 的视图和一个权重为 9 的元素。但是如果你想在一行中添加 10 个视图(每个视图的高度的 1/10)——你可以使用 GridView 或 TableLayout。

这里有两个嵌套的 LinearLayouts 和左上角的 TextView 的答案,TextView 是宽度的 10% 和高度的 10%。 只是为了证明它只适用于一种视图。

<LinearLayout
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:weightSum="10"
    android:background="#FF0000"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="0dp"
        android:orientation="vertical"
        android:weightSum="10"
        android:background="#00FF00"
        android:layout_weight="1"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:background="#000000"
            android:layout_weight="1"
            android:text="Hello"
            android:textColor="#FFFFFF"
         />

    </LinearLayout>

  </LinearLayout>