Search code examples
javaandroidxmlimageviewposition

Positional differences between creating views in XML or programatically


I have a trouble while creating a kind of view. Let's just say that i'm trying to create something similar to a clock. This means that we have to position numbers in a distance and angle from a center.

I tried to emulate a way to position two elements. A center ImageView and a clock number. In XML I have something similar to:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lyt_rootView"
    android:orientation="vertical"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/ivCenter"
        android:background="@drawable/cid"/>

    <ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/ivNumber"
        android:background="@drawable/add_big"
        android:layout_marginLeft="-50dp"
        android:layout_marginTop="50dp"/>

</RelativeLayout>

And it works pretty well, the images set as they should be, being completly centered the first image (ivCenter) and taking some margin from the center for positioning the second image.

Now I have to do the same programatically so I can create lots of imageViews simulating the numbers. So I have this code:

RelativeLayout lyt = (RelativeLayout) findViewById(R.id.lyt_rootView);
int avatarSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70, getResources().getDisplayMetrics());
int distance = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, getResources().getDisplayMetrics());

// center image
ImageView ivImageCenter = new ImageView(this);
ivImageCenter.setImageResource(R.drawable.cid);
RelativeLayout.LayoutParams lp = new     RelativeLayout.LayoutParams(avatarSize,avatarSize);
lyt.addView(ivImageCenter, lp);


// first image (simulating a number in a clock)
ImageView ivNumber1 = new ImageView(this);
ivNumber1.setImageResource(R.drawable.add_big);
RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(avatarSize,avatarSize);
lp2.setMargins(distance, distance, 0, 0);
lyt.addView(ivNumber1, lp2);

but the result is not similar as the XML example. I don't see what I'm missing. The result of creating the views programatically is that the two imageViews are trying to position in a center space in the screen making the first image not centered to the screen.

What I'm missing?


Solution

  • Finally I solved it by creating a one pixel layout centered in XML that acts as a reference and programatically adding the views in that reference view.