0

i am creating an app where I want to change position of my image (imageview) at runtime. I am not able to do it. I am using Linear Layout. Please can anyone give me specific code to do so.

I tried following code (from stackoverflow) but dint work :

ImageView leaf = (ImageView)findViewById(R.id.imageView1);

LayoutParams par = leaf.getLayoutParams();
par.leftMargin += 30;

leaf.setLayoutParams(par);

There was no method called setLayoutParams()

Mat
  • 202,337
  • 40
  • 393
  • 406
swapyy
  • 1
  • 1

5 Answers5

1

You could use a TranslateAnimation (with fillAfter set to true - see sample) for that. Depending whether you want any delay, set the delay time to 0, or if you want to see it animated, set it higher.

Sample: translate animation

Community
  • 1
  • 1
Mathias Conradt
  • 28,420
  • 21
  • 138
  • 192
1

If you MUST use Absolute (and you shouldn't), and you MUST move something at run-time, you can just make a second ImageView and choose in the code which one to use:

I had a little cartoon character which needed to be at the bottom of the screen all the time--one of his animations was jumping out of the way of the menu (kind of looked silly on devices where he was nowhere near it).

The code selects which ImageView to use based on the screen resolution returned from the device. It's not elegant,but it does work, and as long as you pay attention to naming etc should be safe.

*NOTE: On my tests so far, as long as each ImageView was not initialized in xml with a 'src' image, neither will be visible until you assign something to them (so no worries about what to do with the other one).

0

There is definitely a method called

android.view.View.setLayoutParams(LayoutParams params)

You must have some other problem here. I just tested it for one of my ImageViews and was able to change the image's size at runtime.

Anton Kaiser
  • 713
  • 6
  • 11
0

If you want to move the imageview only until the next layout pass, then use

ImageView leaf = (ImageView)findViewById(R.id.imageView1);
leaf.offsetLeftAndRight(30);

Otherwise create new layout params like others suggested.

Ron
  • 24,175
  • 8
  • 56
  • 97
-2

You need to make a new LayoutParams before modifying it. I'm not sure why, but it works for me:

params = new RelativeLayout.LayoutParams(leaf.getLayoutParams());
par.leftMargin += 30;
leaf.setLayoutParams(params);
Li_W
  • 759
  • 1
  • 5
  • 15