ImageView within an AbsoluteLayout, How to set x, y coordinates of the ImageView?

Szuturon picture Szuturon · Dec 2, 2011 · Viewed 9.4k times · Source

What I'm trying to do is create a poorman's version of a gps map. I've setup a "map" picture as the background of an AbsoluteLayout, and then created a tiny 20x20 square picture that I need to move to different coordinates. How do I go about doing this in the Java code?

 <AbsoluteLayout
    android:id="@+id/llMapContainer"
    android:layout_width="match_parent"
    android:layout_height="390dp"
    android:layout_x="0dp"
    android:layout_y="44dp"
    android:background="@drawable/a4000vert"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imgLocation"
        android:layout_width="20px"
        android:layout_height="20px"
        android:layout_x="312px"
        android:layout_y="300px"
        android:src="@drawable/location" />
</AbsoluteLayout>

I have this setup in my Java file: iv = (ImageView) findViewById(R.id.imgLocation);

but now I can't seem to find any methods that would allow me to set the x and y coordinates.

Answer

Trevor picture Trevor · Dec 2, 2011

AbsoluteLayout is depreciated and its use is strongly discouraged. You should switch to using some other form of ViewGroup, such as RelativeLayout.

Once you're using RelativeLayout, you can use the RelativeLayout.LayoutParams class to specify the child's size and position (as well as various other parameters) when adding it to the parent RelativeLayout.

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100,200); // The desired size of the child
params.setMargins(50,50); // Position at 50,50
mRelativeLayout.addView( mViewToAdd, params);