Counter-intuitively, you can do absolute positioning using a RelativeLayout
. (There also exists an AbsoluteLayout
in Android, but its use is deprecated.) Here’s a good answer on stackoverflow on how to do it from Java, but you can also set up objects on a RelativeLayout
in the XML layout designer:
You can position the ImageViews with the mouse, but here is what the XML looks like. Note the properties layout_marginLeft
and layout_marginTop
in the ImageViews.
<?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="Hello World, MyActivity"
android:id="@+id/textView" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_alignParentLeft="true"
android:layout_marginLeft="22dp"
android:layout_alignParentBottom="true"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/pinkRabbit"
android:src="@drawable/pink_rabbit_smile_animal_elonizm_pet"
android:layout_toRightOf="@+id/button"
android:layout_alignParentTop="true"
android:layout_marginTop="52dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/greenRabbit"
android:src="@drawable/rabbit_animal_green"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dp"
android:layout_alignParentTop="true"
android:layout_marginTop="21dp"/>
</RelativeLayout>
</LinearLayout>
Here is a program that, when you click on the text view, moves the green rabbit to the right.
public class MyActivity extends Activity implements View.OnClickListener {
View greenRabbit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View textView = findViewById(R.id.textView);
greenRabbit = findViewById(R.id.greenRabbit);
textView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams params;
params = (RelativeLayout.LayoutParams) greenRabbit.getLayoutParams();
params.leftMargin += 25;
greenRabbit.setLayoutParams(params);
}
}
And a demo video:
The two images I used in this project, in case you want to grab them: