【问题标题】:Android: Using LayoutParams to set width of View objectAndroid:使用 LayoutParams 设置 View 对象的宽度
【发布时间】:2023-03-17 11:41:01
【问题描述】:

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

感谢您的帮助。

【问题讨论】:

  • 右边的填充物怎么样?

标签: android android-layout android-ui android-view layoutparams


【解决方案1】:

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

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

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

【讨论】:

  • 我更担心我在矩形块中看到的额外宽度,而不是圆圈被切断的事实。圆圈被切断只是因为矩形块将它们推离测量宽度的边界。我只是想让蓝色块占据绿色圆圈不占据的所有空间。
  • 抱歉,还有一条评论:绿色圆圈不是图像。它们是单独定义的 XML 可绘制形状,定义如下: schemas.android.com/apk/res/android" android:shape="oval"> 所以我独立定义了形状,并且然后我在我之前发布的 XML 中使用该形状,并在那里给它一个大小。
  • 嗯明白了,谢谢指正。您不想将所有三个视图的布局权重都设置为 1,这意味着您希望它们都具有相同的宽度。只需将块设置为 1 的 layout_weight,并将圆圈设置为没有重量的任何大小。尝试一下(并将块宽度设置为 fill_parent 以外的其他值)。
猜你喜欢
  • 2012-08-21
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 2016-06-25
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
相关资源
最近更新 更多