0

I am trying to change the position of an Imagebutton after the user clicks it. I am not sure how to get it to change position to only inside of the RelativeLayout I have placed over an ImageView. It will not go out on the left or top but it will go outside the screen on the right and bottom. Is there a way to set the button's random function so that it will only appear randomly inside of this RelativeLayout I have set up and not outside the screen like it is doing now?

I have attached my XML and JAVA code:

XML CODE:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" 
android:background="#000000"
android:id="@+id/window">


<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:src="@drawable/buttonfield" />

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignTop="@+id/imageView1" 
    android:layout_alignBottom="@+id/imageView1"
    android:id="@+id/layout">

    <ImageButton
    android:id="@+id/btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:background="@drawable/tapadot_dot_start"/>

</RelativeLayout>

</RelativeLayout> 

JAVA CODE:

package com.example.randombutton;

public class MainActivity extends Activity {

private ImageButton startbutton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);



    final ImageView field = (ImageView) findViewById(R.id.imageView1);
    startbutton = (ImageButton) findViewById(R.id.btn);


    startbutton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {


        Random r = new Random();
        int buttonHeight;
        int buttonWidth;
        buttonHeight = startbutton.getHeight();
        buttonWidth = startbutton.getWidth();

        int x = r.nextInt(480 + buttonWidth);
        int y = r.nextInt(900 + buttonHeight); 


        startbutton.setX(x); 
        startbutton.setY(y);

        }
        }});

    }

}
Onik
  • 19,396
  • 14
  • 68
  • 91
user3689022
  • 17
  • 1
  • 6
  • You need to write a custom view class (a class that extends some View) and handle this in it's onDraw method. – zgc7009 Jul 21 '14 at 22:45
  • Any way you could show some example code of that because I am not sure exactly how to implement that in my existing code? @zgc7009 – user3689022 Jul 22 '14 at 00:26

0 Answers0