Androidでは、Viewを配置する時は基本的に相対位置で指定する。
Androidの場合は端末によって解像度がまちまちなため、相対位置で指定することは理にかなっている。
しかし、時には絶対位置で指定したいこともある。
以前はそれを実現するためのAbsoluteLayoutというものがあったがSDK1.5以降、非推奨となってしまった。
Androidはソースが公開されているからAbsoluteLayoutのソースを参照して自前で実装する、というのも
対応策の一つではあるが、そこまでしなくてもRelativeLayoutを使うことで十分代替できる。
どうするかというと、layout_marginTopとlayout_marginLeftを使って以下のように指定すればよい。
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="wrap_content" android:layout_height="40dp" android:text="button1" android:layout_marginTop="50dp" android:layout_marginLeft="100dp" ></Button> <Button android:layout_width="wrap_content" android:layout_height="40dp" android:text="button2" android:layout_marginTop="150dp" android:layout_marginLeft="100dp" ></Button> </RelativeLayout> </LinearLayout>
layout_marginTopは親要素の上からの位置、layout_marginLeftは親要素の左からの位置だからそれぞれx座標、y座標という風に読み替えれば良い。
実行すると以下のようになる。
ピンバック: コピペプログラマが音ゲーを作ろう~その7~ – 3535ACEのぐだぐだ集