如何将View的顶部与另一个View的垂直中心对齐?

时间:2013-06-06 09:18:55

标签: android relativelayout

我需要将View2左上角与View1的中心对齐,但我无法弄明白该怎么做。

enter image description here

3 个答案:

答案 0 :(得分:1)

这是怎么做的!

制作像

这样的xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="200dp"
    android:background="#FFFF99" >

    <LinearLayout
        android:id="@+id/view1"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="10dp"
        android:background="#440000"
        android:orientation="horizontal" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/view1"
        android:layout_alignTop="@id/view1"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/view2"
            android:layout_width="200dp"
            android:layout_height="100dp"
            android:background="#99004400"
            android:orientation="horizontal" >
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

在你的活动中

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
         LinearLayout v1=(LinearLayout)findViewById(R.id.view1);
            LinearLayout v2=(LinearLayout)findViewById(R.id.view2);
            LinearLayout container=(LinearLayout)findViewById(R.id.container);
            int heightV1=v1.getHeight();
            int widthV1=v1.getWidth();
            container.setPadding(widthV1/2, heightV1/2, 0, 0);
    }

提供类似

的输出

enter image description here

答案 1 :(得分:0)

试试这个

  RelativeLayout.LayoutParams gpsViewLayoutParams = new     RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT );
gpsViewLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
gpsViewLayoutParams.addRule(RelativeLayout.ALIGN_RIGHT);
this.relativeLayout.addView(gpsView,gpsViewLayoutParams); 

答案 2 :(得分:-3)

这对你有什么帮助吗?

<RelativeLayout>
<View1 />
<View2
 Layout_marginTop= (view1Height/2)+view1margin
 Layout_marginLeft=(view1Width/2)+view1margin /> 
</RelativeLayout>