我在具有自定义宽度的 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”,但这根本没有任何影响。知道为什么我的块超出了我希望它扩展的宽度吗?
谢谢你的帮助。