I want to show a rectangular box in the absolute center in a layout with height h/3 and width 3w/5 (w: width of screen, h: height of screen). Please help me to find a solution, Thanks in advance.
Asked
Active
Viewed 2,287 times
3 Answers
3
Yeah. This is possible using a Relative layout parent and another layout(your box) inside that positioned as center. and the width and height of your box can be mentioned in java, rather than in xml.

DGN
- 702
- 3
- 12
3
you can adjust it using linear layout using weight i have pasted a sample code 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"
/>

varun thomas
- 357
- 4
- 14
2
Create a custom view which extends the View
class and override the onDraw()
method to create the desired rectangle. you can refer to: Android canvas draw rectangle to get the general idea.
If your question is: How to position a view inside a container - add this in 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 instance
is a reference to your container view.