2

我在具有自定义宽度的 Android 应用程序中使用了一个 UI 元素。UI 元素本质上是一个带有两个绿色圆圈的块 - 一个圆圈在块的左侧,另一个圆圈在块的右侧。

我希望能够以编程方式设置整个 UI 元素的宽度。圆圈应始终具有恒定大小,然后位于中间的块应自行调整大小以填充其余空间。

这是我目前拥有的:

<?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="horizontal" >

    <View
        android:background="@drawable/green_circle"
        android:id="@+id/left_green_circle"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
    />

    <View
        android:background="@drawable/blue_rectangle"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal" 
    />

    <View
        android:background="@drawable/green_circle"
        android:id="@+id/right_green_circle"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
    />

</LinearLayout>

然后我在代码中设置视图的布局参数,如下所示:

int layoutLeft = block_x_position - green_circle_width;
int layoutWidth = block_width + (green_circle_width * 2);

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(layoutWidth, block_height);
layoutParams.setMargins(layoutLeft, block_y_position, 0, 0);
this.setLayoutParams(layoutParams);

this.requestLayout();

我在上面的代码中使用了RelativeLayout,因为整个View 元素的父级是RelativeLayout。不幸的是,我没有得到我期望的结果。我的“block_width”变量是“40dp”,我的“green_circle_width”变量是“20dp”。这是我得到的:

在此处输入图像描述

我尝试在我的 View XML 中使用“wrap_content”而不是“match_parent”,但这根本没有任何影响。知道为什么我的块超出了我希望它扩展的宽度吗?

谢谢你的帮助。

4

1 回答 1

1

您看到的圆圈是因为(我想)绿色圆圈图像(jpg 或 png)的宽度大于 20dp。如果要缩放绿色圆圈,请使用 imageView 并设置 scaleType 属性。

否则你得到的正是你想要的。通过将圆形视图强制为 20dp,您正在为块填充创建大量额外空间。正确设置圆圈宽度或使用 scaleType 即可。

顺便说一句,您可能不应该使用 match_parent 作为块的宽度(这意味着它将占据整个宽度,包括应该被圆圈占据的空间)。而是使用一些任意宽度(例如 0dp)并将 layout_weight 设置为 1。

于 2011-12-29T21:39:26.617 回答