我有一個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