I had a button that inside A layout, if the button clicked it was make Random Position method to button in every second button will move Randomly
So this is the view of my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="@+id/layout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="30dp"
android:background="@drawable/backgroundblankred" >
<Button
android:id="@+id/button1"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/eeclevelfirstblackbuton" />
</RelativeLayout>
</RelativeLayout>
so this is the code to make the button move inside layout1 and not out from there
import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
Button buttonblack;
RelativeLayout layout1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout1 = (RelativeLayout)findViewById(R.id.layout1);
buttonblack = (Button)findViewById(R.id.button1);
buttonblack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startRandomButton(buttonblack);
}
});
startRandomButton(buttonblack);
}
public static Point getDisplaySize(@NonNull RelativeLayout layout12) {
Point point = new Point();
return point;
}
private void setButtonRandomPosition(final Button button){
//make the button not out from the layout1
int randomX = new Random().nextInt(getDisplaySize(layout1).x);
int randomY = new Random().nextInt(getDisplaySize(layout1).y);
button.setX(randomX);
button.setY(randomY);
}
private void startRandomButton(Button button) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
setButtonRandomPosition(buttonblack);
}
}, 1000, 1000);//Update button position every second
}
but the app was force close when i open it, anyone can correct the problem with my code in there? Thank's.
Aucun commentaire:
Enregistrer un commentaire