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

时间:2014-07-10 15:30:57

标签: android android-layout runtime android-view

我以编程方式生成我的视图,因此没有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。使用this和maxLines,此TextView的最大区域大小为300dp x 3 lines。最有可能的是,TextView不会很大,而wrap_content设置,TextView和LinearLayout将适应文本。
(我不得不说,我覆盖了TextView&#39; 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,但我无法找到它。
此外,这些是移动LinearLayout的正确方法和地点吗?因为我需要TextView的最终大小,所以必须进行测量,所以这是我必须要做的地方,我认为。

修改
我尝试了一点。我从LinearLayout获得LayoutParams,增加左边并通过计算的平移减少右边距并再次设置LayoutParams。好吧,ImageView仍然保留在原位,所以这里没有进展。但是在关闭应用程序后,我意识到,每次布局都会改变保证金。那么,应该看到这一点 但是为什么使用setLeft和setRight不会发生同样的事情?

1 个答案:

答案 0 :(得分:0)

也许如果你画出你想要的图片会有所帮助。

我会完全不使用onLayout方法。

如果要移动视图或布局,请使用布局参数

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