简体   繁体   中英

Center view contents in screen

I've been porting a Java game to Android, and I now have essentially only one step remaining: the original desktop version created a window and drew in a big black box the same size. The entire game field is less than the resolution of a standard Android device, but readably so, so I'd like to simply retain all the coordinates as we know them and center playing field in the screen, extending the border in all directions.

Now, I could go and find all the various draw methods and add the appropriate offset, or I could simply (though I do not know how) embed the view in another, and simply move 0,0 in the playfield by the appropriate offset. The latter is my strongly preferred, but I simply don't know where to begin!

Any ideas?

If you are totally sure that your contents will fit the display and you just want to center it inside a layout, assuming that the size of your game is (eg 320x200) you could start from something like this:

Just create a xml layout file with a root FrameLayout ( consider this a pointer: I didn't test this code ):

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#000000"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <YourView
        android:id="@+id/myview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
</FrameLayout>

The game content should be centered on the screen and the black border of "YourView" will overflow the screen.

Hope this helps

NOTE : edited the layout_width/height parameters (as setting the content size inside them yields an incorrect result, unless your view is honoring something similar to android:gravity parameter).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM