Pspl
Pspl

Reputation: 1474

Add imageview programmatically constraints problem

I'm building an app (for Android) using Android Studio and I'm facing some troubles regarding the position of a programmatically added ImageView to my FrameLayout.

First things first: I have an initial ImageView on that FrameLayout called AVATAR01 as you can see on the xml file:

<FrameLayout
    android:id="@+id/LayJog"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="0dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">
    <ImageView
        android:id="@+id/AVATAR01"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@drawable/avatar01" />
</FrameLayout>

Then I use the next JAVA piece of code to add another ImageView similar to the one I already declared before:

//Objects:
    ImageView IMG01 = (ImageView) findViewById(R.id.AVATAR01);
    FrameLayout LAYJOG = (FrameLayout) findViewById(R.id.LayJog);
    ViewGroup.LayoutParams LAYPAR = new ViewGroup.LayoutParams(IMG01.getLayoutParams());
    ViewGroup.MarginLayoutParams MARPAR = new ViewGroup.MarginLayoutParams(IMG01.getLayoutParams());
//New ImageView:
    ImageView IMG02 = new ImageView(getApplicationContext());
    IMG02.setLayoutParams(new ViewGroup.LayoutParams(LAYPAR));
    IMG02.setLayoutParams(new ViewGroup.MarginLayoutParams(MARPAR));
    IMG02.setTop(100);
    IMG02.setImageResource(R.drawable.avatar02);
    LAYJOG.addView(IMG02);

The code above doesn't has any runtime errors, but the program places the new image at position (0, 0) of the FrameLayout. I'm pretty sure this is something to do with the constraints settings of the new ImageView I added, but I'm not able to fix this. Does anyone knows how can I place the new ImageView at position (10, 100)? Thanks.

Upvotes: 1

Views: 110

Answers (1)

Sina Soheili
Sina Soheili

Reputation: 123

I think you can solve this problem by adding margin to ImageView. for example :

LinearLayout layout = findViewById(R.id.layout);

    ImageView IMG02 = new ImageView(this);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT , LinearLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(LEFT , TOP , RIGHT , BOTTOM);
    IMG02.setLayoutParams(layoutParams;

    layout.addView(IMG02);

you must insert your value instead of "LEFT , TOP , RIGHT , BOTTOM"

Upvotes: 1

Related Questions