1

i want to add a view to a relativelayout. this view must be added to a specified position.

i have this:

    int x = ...;
    int y = ...;
    button.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();
            v.layout(x, y, x + v.getWidth(), y + v.getHeight());
            return true;
        }
    });
    relativelayout.addView(button);
    button.layout(x, y, x + button.getWidth(), y + button.getHeight());

the ontouchlistener works great.. the view stays with my finger. however the startpostion is always 0, 0... it doesn't matter what my x and y is.

anyone a idee?

Doomic
  • 337
  • 2
  • 15

2 Answers2

6

i have a workaround.

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp.leftMargin = x;
lp.topMargin = y;
relativelayout.addView(tmpTextButtonView, lp);

it is not great to use margin for positioning floating views. however it works for me.

Doomic
  • 337
  • 2
  • 15
  • It is not the workaround. It is one of the two normal ways. The other one is to getLayoutParams, change them and set back. .layout() is some service function, that you need if you create your own descender of ViewsGroup. – Gangnus Jan 30 '12 at 13:56
1

You might want to try setting the position of your button before you add it to the parent view. So just swap these two lines:

relativelayout.addView(button);
button.layout(x, y, x + button.getWidth(), y + button.getHeight());

to be this:

button.layout(x, y, x + button.getWidth(), y + button.getHeight());
relativelayout.addView(button);
Andrea Thacker
  • 3,440
  • 1
  • 25
  • 37