カスタム幅を持つ Android アプリで使用している UI 要素があります。UI 要素は基本的に、2 つの緑色の円を含むブロックです。1 つの円はブロックの左側にあり、もう 1 つの円はブロックの右側にあります。
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>
次に、View in code のレイアウト パラメータを次のように設定します。
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();
この View 要素全体の親が RelativeLayout であるため、上記のコードで RelativeLayout を使用しています。残念ながら、期待した結果が得られていません。私の「block_width」変数は「40dp」で、「green_circle_width」変数は「20dp」です。ここに私が得ているものがあります:
ビュー XML で「match_parent」の代わりに「wrap_content」を使用してみましたが、まったく影響がありません。拡張したい幅を超えてブロックが拡張される理由は何ですか?
助けてくれてありがとう。