Search code examples
androideclipseandroid-layoutbasic4android

Android - layout width/height percentage of a screen?


I was testing out B4A (Basic4Android) and there's something called a "designer script", this basically allows you to position elements on a screen. For example:
TextBox1.setTopAndBottom(0%y, 50%y)
TextBox1.setLeftAndRight(0%x, 50%x)

When this script runs it will automatically position the TextBox1 on the screen, imagine the the screen is 100 pixels by 100 pixels (100x100), the TextBox1 will be placed at (0, 0) (top left), (50, 50) (bottom right).

How can I achieve something like this in Eclipse?
I can't figure it out. I want to position an element (TextBox1 for example) to fit 25% of the width and 50% of the height for example. How do I achieve this?


Solution

  • OK. This is the trick

    In simple words: make a 1px (px, not dp - you don't want it scaled, but small enough to be trascurable!) TextView which will be your invisible (you leave it transparent and set no text in it) "center of the universe".
    Then stretch your other TextView, but limit it to stay to the left (which is at 50% - 1/2 px) of the center and above (again, 50% - 1/2 px) it:

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <TextView
            android:id="@+id/centerPoint"
            android:layout_width="1px"
            android:layout_height="1px"
            android:layout_centerInParent="true"
        />
        <TextView
            android:id="@+id/myText"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_toLeftOf="@id/centerPoint"
            android:layout_above="@id/centerPoint"
        />
    </RelativeLayout>