使自定义视图使用布局权重



我正在尝试制作一个具有以下布局的android应用程序

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.CustomView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:id="@+id/customView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:weightSum="2"
android:orientation="horizontal">
<TextView
android:id="@+id/TopLeftText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" />
<TextView
android:id="@+id/TopRightText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:weightSum="2"
android:orientation="horizontal">
<TextView
android:id="@+id/BottomLeftText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" />
<TextView
android:id="@+id/BottomRightText"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" />
</LinearLayout>
</LinearLayout>
</LinearLayout>

并且应该像这样布局

+---+---+
|       |
|       |
|       |
|   c   |
|       |
|       |
|       |
+---+---+
|   |   |
| t | t |
|   |   |
+---+---+
|   |   |
| t | t |
|   |   |
+---+---+

其中c是我的自定义视图,t是文本视图。我已经在垂直模式下使用一个线性布局将文本视图放在网格中,其子级layout_weights设置为1,然后在水平模式下使用子级线性布局并将其子级文本视图的布局权重设置为1。但由于某种原因,我似乎无法让我的自定义视图共享半个线性布局,即使设置了权重。我的屏幕目前看起来更像:

+---+---+
|       |
|       |
|       |
|       |
|       |
|   c   |
|       |
|       |
|       |
|       |
|       |
|       |
|       |
+---+---+
| t | t |
+---+---+
| t | t |
+---+---+

我似乎什么也没做,这一观点只占了一半的高度。我的观点大致如下:

class CustomView extends View {
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
}
protected void onDraw(Canvas canvas) {
// here I just have some code to fill the view in with solid colour
}
}

这个类是从一个XML文件构建的,我试过扰乱layout_width、layout_height、layout_weight、layout_gravity,但似乎没有什么能解决它

使用权重时,应该使用0dp的高度/宽度。使用wrap_content有时会导致意外的结果。

最新更新