0

To drag the Image on the screen I created my own class:

private class CustomImageView extends AppCompatImageView

In the constructor I want to set params:

public CustomImageView(Context context) {
    super(context);
    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    params.bottomMargin = 50;
    this.setScaleType(ImageView.ScaleType.CENTER_CROP);
    this.setLayoutParams(params);
    this.setWillNotDraw(false);
}

my activity_main.xml:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.eleizo.firstapplication.MainActivity">   
</RelativeLayout>

I want to have actually as it would be :

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.eleizo.firstapplication.MainActivity">

    <ImageView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        android:layout_marginBottom="50dp"
        />
</RelativeLayout>

Why string "params.bottomMargin = 50" doesn't work? I tried to set params = new RelativeLayout.LayoutParams(val1,val2) but it's no matter. How set android:layout_marginBottom in RelativeLayout by code?

Ajil O.
  • 6,562
  • 5
  • 40
  • 72
Elena
  • 25
  • 7

2 Answers2

0

Try using MarginLayoutParams instead of LayoutParams.

if( params instanceof MarginLayoutParams )
{
    ((MarginLayoutParams) params).bottomMargin = 50;
    ((MarginLayoutParams) params).leftMargin = 10;

}

So your code would look like

public CustomImageView(Context context) {
    super(context);
    params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

    if( params instanceof MarginLayoutParams )
    {
    ((MarginLayoutParams) params).bottomMargin = 50;
    }
    this.setScaleType(ImageView.ScaleType.CENTER_CROP);
    this.setLayoutParams(params);
    this.setWillNotDraw(false);

}

Kapil G
  • 4,081
  • 2
  • 20
  • 32
0

try using the LayoutParams while you are adding the view in the relative layout. ViewGroup.addView(View, LayoutParams) .

Something like this.

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
params.bottomMargin = 50;

relativeLayout.addView(new CutomImageView(context), params);
umuieme
  • 729
  • 6
  • 20