我有一个UI元素,我正在使用具有自定义宽度的Android应用程序。 UI元素本质上是一个带有两个绿色圆圈的块 - 块左侧为一个圆圈,块右侧为另一个圆圈。Android:使用LayoutParams设置查看对象的宽度
我希望能够以编程方式设置整个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”。下面是我得到:
我一直在使用,而不是在我查看XML“match_parent”“WRAP_CONTENT”试过,但没有任何影响的。任何想法,为什么我的块越来越超出我希望它被扩展的宽度?
感谢您的任何帮助。
如何将一些填充移到右侧? – bluejamesbond 2011-12-29 20:39:44