Search code examples
androidandroid-relativelayoutandroid-layoutparams

How set android:layout_marginBottom programm?


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?


Solution

  • 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);