Android - Align view center to bottom of other view

后端 未结 7 902
小蘑菇
小蘑菇 2020-12-31 00:57

A picture tells more than a lengthy speech :

I want to align vertically the center of the red part with the middle of the black part. I have no constraint of contai

相关标签:
7条回答
  • 2020-12-31 01:45

    Finally, I use a more programmatic way to solve this problem, because the size of Views are not fixed.

    Here the solution :

    The layout :

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
    
                <View
                    android:id="@+id/black"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"/>
    
                <View
                    android:id="@+id/red"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true">
            </RelativeLayout>
    

    The code :

                red.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        red.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    
                        LayoutParams params = new LayoutParams(
                                LayoutParams.MATCH_PARENT,      
                                LayoutParams.WRAP_CONTENT
                                );
                        params.setMargins(0, 0, 0, red.getHeight()/2);
                        black.setLayoutParams(params);
                    }
                });
    

    Thanks for your help ! It helps me found this !

    0 讨论(0)
提交回复
热议问题