0

I have Framelayout with 2 components

  • Linear layout
  • ImageView

I want to set android:layout_marginTop="100dp" to the Imageview (programatically )

Stackoverflow solutions says :

ImageView imgv = (ImageView)findViewById(R.id.redLine);
FrameLayout frameLayout= (FrameLayout)findViewById(R.id.frameLayout);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) frameLayout.getLayoutParams();
layoutParams.setMargins(100, 0, 0, 0);
imgv.setLayoutParams(layoutParams);

But I get Cast exception :

ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.FrameLayout$LayoutParams

Question

How can I set this :android:layout_marginTop="100dp" to the Imageview (programatically ) ?

Additional info :

enter image description here

Imports :

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

2 Answers2

1

Here's a slightly more educational answer to your own solution:

LayoutParams are always of the type of the container a View (or ViewGroup) is added to. They relate to the 'parent' of the view, if you like.

In your example:

  • The FrameLayout is added to a LinearLayout, hence its layout params are of type LinearLayout.LayoutParams.
  • The ImageView is added to a FrameLayout, hence its layout params are of type FrameLayout.LayoutParams.

With this information you should be able to deduce what's going wrong.

Spoiler: you're making the common mistake of thinking that the layout params of the FrameLayout are of type FrameLayout.LayoutParams. However, as they relate to the layout's parent, they're actually of type LinearLayout.LayoutParams. Hence the class cast exception.

MH.
  • 45,303
  • 10
  • 103
  • 116
0

Got it :

      FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      params.setMargins(200, 1, 1, 1);
      imgv.setLayoutParams(params);
Royi Namir
  • 144,742
  • 138
  • 468
  • 792