1

First of all sorry for my English. I just began development with android

My problem is:

I create an ImageView in a random position, every time you touch the image, it change its position. When you touch you have a probability (%) that appears another Image in another random position. But my problem is when the second image appear, the first one come back to its "created position" and not keeping position.

The "Bomb" is created well, but then the first image back to created position and not the position it is in the moment.

Thanks all for the help

Example of my test code:

public void start(View view) {
    width= 60;
    height= 60;
    layout = (RelativeLayout) findViewById(R.id.rellayout);
    widthLayout = layout.getWidth();
    heightLayout = layout.getHeight();
    r = new Random();
    x = r.nextInt(widthLayout - 60);
    y = r.nextInt(heightLayout - 60);

    imagen = new ImageView(this);
    imagen.setImageResource(R.drawable.led_circle_green);
    RelativeLayout.LayoutParams paramss = new RelativeLayout.LayoutParams(
            60, 60);
    paramss.leftMargin = x;
    paramss.topMargin = y;
    imagen.setAdjustViewBounds(true);
    layout.addView(imagen, paramss);

    Animation aparecer = AnimationUtils
            .loadAnimation(this, R.anim.aparecer);
    imagen.startAnimation(aparecer);

    imagen.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            // your code here
            push();
        }
    });


  public void push() {
    createBomb();
    move();
}

public void createBomb() {
    r = new Random();
    int proba = r.nextInt(100);

    if (proba < 50) {   
        x = r.nextInt(widthLayout - 60);
        y = r.nextInt(heightLayout - 60);

        bomb = new ImageView(this);
        bomb.setImageResource(R.drawable.bomb);

        RelativeLayout.LayoutParams paramss = new RelativeLayout.LayoutParams(
                60, 60);
        paramss.leftMargin = x;
        paramss.topMargin = y;
        bomb.setAdjustViewBounds(true);
        layout.addView(bomb, paramss);
    }
}

public void move() {
    r = new Random();
    int proba = r.nextInt(100);

        if (proba < 10) {

                ximg = r.nextInt(widthLayout - width);
                yimg = r.nextInt(heightLayout - height);


            imagen.layout(ximg, yimg, ximg + width, yimg + height);

        }

}
nsgulliver
  • 12,655
  • 23
  • 43
  • 64

1 Answers1

0

layout method does not applies persistent changes to a view state. Set new layout params to image view, which will specify it's new position (do not use layout method).

When you add new ImageView2 RelativeLayout decides to relayout its childs and resets ImageView1 position.

Read this.

Community
  • 1
  • 1
Leonidos
  • 10,482
  • 2
  • 28
  • 37