Show rectangular box in absolute center in layout

I want to show a rectangular rectangle in the absolute center in a layout with height h / 3 and width 3w / 5 (w: screen width, h: screen height). Please help me find a solution, thanks in advance.

+5
source share
3 answers

you can customize it using a linear layout using weight I inserted the code example below, hope this helps.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@color/transparent"
 >

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="horizontal"
>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="5"
 />
 <TextView
    android:id="@+id/desiredbox"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="TextView"
    android:layout_gravity="center"
    android:background="@color/skyblueBackground" 
    android:layout_weight="1"
    />
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="5"
 />
 </LinearLayout>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/>

+3
source

Yes. This is possible using the parent element Relative layout and another layout (your box) located inside the center. and the width and height of your box can be specified in java, not in xml.

+3
source

, View onDraw() . : Android, .

If your question is: how to place the view inside the container - add it to the constructor of the parent view:

    final ViewTreeObserver vto = this.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
                // here, the dimensions of the parent are available
                int containerHeight = instance.getHeight();
                int containerWidth = instance.getWidth();       

                childView.setY(containerHeight/3);
                childView.setX(containerWidth * 3 / 5);
                instance.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            }       
        }
    });

where instanceis a link to your container view.

+2
source

All Articles