对齐视图:更改锚点的位置并更新对齐视图的位置



我以编程方式生成视图,因此没有XML。但是为了更容易显示我的问题,我将以类似xml的符号

给出该结构。
<RelativeLayout
    android:id="@+id/mainLayout">
    <LinearLayout
        android:id="@+id/left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:maxWidth="300dp"
            android:maxLines="3"
            android:text="Some long Text" />
    </LinearLayout>
    <ImageView
        android:id="@+id/right"
        android:layout_toRightOf="@id/left">
</RelativeLayout>

对于这个,LinearLayout被定位在RelativeLayout的左上角。ImageView位于它的右边。
TextView非常重要。你可以看到它的宽度是可变的,但最大为300dp。有了这个和maxLines,这个TextView有一个300dp x 3 lines大小的最大面积。最有可能的是,TextView不会这么大,通过wrap_content设置,TextView和LinearLayout将适应文本。(我不得不说,我重写了TextView的onMeasure方法,所以TextView只和最宽的线一样宽。)
目前,一切都很好。TextView和LinearLayout紧紧地包围了文本,位于(0,0),旁边是ImageView。现在是我被困住的最困难的部分。

我想在前面提到的区域内对齐LinearLayout, TextView可以最大限度地跨越。第一个想法是,我用另一个RelativeLayout包围LinearLayout,通过最大尺寸和较小的LinearLayout位置。但是由于ImageView 必须必须是mainLayout的直接子元素,我不能再将它与LinearLayout对齐了。我目前的方法是覆盖LinearLayout的onLayout方法:

@Override
protected void onLayout(boolean changed, int left, int top,
                                         int right, int bottom){
    super.onLayout(changed, this.getLeft(), this.getTop(),
                            this.getRight(), this.getBottom());
    int translation;
    int widthNeed = this.mLinLay.getMeasuredWidth();
    switch(this.mLinLayAlignment)
    {
        case Left:
            break;
        case Center:
            translation = (this.mLabWidth - widthNeed)/2;
            this.setLeft(this.getLeft() + translation);
            this.setRight(this.getRight() + translation);
            // also tried: this.setTranslationX(translation);
            break;
        case Right:
            translation = (this.mLabWidth - widthNeed);
            this.setLeft(this.getLeft() + translation);
            this.setRight(this.getRight() + translation);
            // also tried: this.setTranslationX(translation);
            break;
    }
}

我现在只想水平对齐LinearLayout,所以我只区分3种情况。转换工作得很好,但是ImageView保持在它的位置上,在那里它对齐到LinearLayout的初始位置。我首先尝试了LinearLayout.setTranslationX(),但效果相同。所以我改变了它,因为setTranslationX的文档暗示,翻译发生在布局之后。
我想我只需要调用正确的方法,所以mainLayout被强制重新布局ImageView,但是我找不到它。
此外,这些是正确的方式和地方来移动线性布局?因为我需要TextView的最终大小,它必须被测量,

我认为这是我需要做的地方。

编辑
我又试了一点。我从LinearLayout中得到了LayoutParams,通过计算的平移增加了左边的边距,减少了右边的边距,并再次设置了LayoutParams。ImageView仍然在原地,这里没有进展。但在切换和返回应用程序后,我意识到,每次布局时边距都会改变。我早该料到会这样。
但为什么使用setLeft和setRight不会发生同样的事情呢?

也许你画一幅你想要的东西会有帮助。

我不会使用onLayout方法。

如果你想移动视图或布局,然后使用布局参数

    RelativeLayout.LayoutParams params = linearLayout.getLayoutParams();
    params.setMargins(left, top, right, bottom);
    linearLayout.setLayoutParams(params);

最新更新