0

I've tried this code to change randomly the button position. But i'ts just dimensions, on the first click the button change position but on the other click not. Why?? some help? Thanks

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
final Button btn = (Button) findViewById(R.id.run_button);
        RelativeLayout.LayoutParams absParams = (RelativeLayout.LayoutParams) btn
                .getLayoutParams();

        DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        int width = displaymetrics.widthPixels;
        int height = displaymetrics.heightPixels;

        Random r = new Random();

absParams.width = r.nextInt(width);
        absParams.height = r.nextInt(height);
        btn.setLayoutParams(absParams);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Random r = new Random();
                btn.getX();
                btn.getY();

                btn.setX(r.nextFloat());
                btn.setY(r.nextFloat());

            }

        });
Fabio Balsamo
  • 59
  • 1
  • 2
  • 11
  • float x = r.nextInt(displaymetrics.widthPixels / 2); float y = r.nextInt(displaymetrics.heightPixels / 2); btn.setX(x); btn.setY(y); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Random r = new Random(); float x = r.nextInt(displaymetrics.widthPixels / 2); float y = r.nextInt(displaymetrics.heightPixels / 2); btn.setX(x); btn.setY(y); – Fabio Balsamo Jul 28 '15 at 15:37

1 Answers1

0

I'm pretty sure the touch positions do not change when you call setX() and setY(). They stay at the original spot. You have to actually change the layout parameters so the layout is informed knows that your view is at that spot. Like so:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //The WRAP_CONTENT parameters can be replaced by an absolute width and height or the FILL_PARENT option)
params.leftMargin = 50; //Your X coordinate
params.topMargin = 60; //Your Y coordinate
childView.setLayoutParams(params);

Taken from: Android - Use of view.setX() and setY in api 8

Community
  • 1
  • 1
TameHog
  • 950
  • 11
  • 23
  • ya...thanks... now work with this code float x = r.nextInt(displaymetrics.widthPixels / 2); float y = r.nextInt(displaymetrics.heightPixels / 2); btn.setX(x); btn.setY(y); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Random r = new Random(); float x = r.nextInt(displaymetrics.widthPixels / 2); float y = r.nextInt(displaymetrics.heightPixels / 2); btn.setX(x); btn.setY(y); – Fabio Balsamo Jul 28 '15 at 15:37