1

Possible Duplicate:
How to set margin of ImageView using code, not xml

I was wondering if there was a way where I could center a view by using SetMargins (Or any other alternatives). I know that you can use gravity but if I do, the MotionEvent also applies with it (So when I drag the image, image goes to the new "center" from where I touched).

OnTouchListener dragt = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent me) {

FrameLayout.LayoutParams par = (FrameLayout.LayoutParams) v.getLayoutParams();
FrameLayout.LayoutParams spawn = (FrameLayout.LayoutParams) v.getLayoutParams();

setMargins only lets me use numbers and it won't have the same results for all devices.

spawn.setMargins(170, 350,0 ,0);

switch (v.getId()) {
case R.id.randomView:
}
switch(me.getAction()) {

case MotionEvent.ACTION_MOVE:
    par.gravity = 0;
    par.setMargins((int)me.getRawX() - (color.getWidth())/2, (int)me.getRawY() - (color.getHeight())/2, 0, 0);
    color.setLayoutParams(par);
    break;

case MotionEvent.ACTION_UP:
    score++;
    textScore.setText(String.valueOf(score));
    color.setImageResource(mImageIds[rgenerator.nextInt(mImageIds.length)]);

Sets the position (refers from above)

    color.setLayoutParams(spawn);       
    break;
        }
return true;
    }
};
Community
  • 1
  • 1
Kurty
  • 475
  • 2
  • 16
  • Possible solutions: http://stackoverflow.com/questions/3416087/how-to-set-margin-of-imageview-using-code-not-xml and http://stackoverflow.com/questions/2481455/set-margins-in-a-linearlayout-programmatically – TryTryAgain Mar 19 '12 at 18:37
  • 1
    I have already read them but I still don't know how to center the view. I know that setMargins only allows me to use px but I want the effect to be like gravity, only that the MotionEvent and OnTouch doesn't affect it. – Kurty Mar 19 '12 at 18:56
  • 1
    That link still does not answer to how I would be able to center the view with/ without setMargins programmatically and get the same results for other devices... – Kurty Mar 21 '12 at 18:20
  • 1
    I have finally found the answer to this. The problem was that I was setting it to the new position but when all along, all I needed to do was reset it to its original position by copying part of the code that set it's position in the beginning. Here is the code if anyone needs it. (I needed to reset the LayoutParams) – Kurty Apr 24 '12 at 02:08
  • color.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER)); – Kurty Apr 24 '12 at 02:09

0 Answers0