vendredi 2 juillet 2021

How to set a button's position to random points on screen?

I am trying to make a button appear in random positions on the screen but it keeps going out for some reason. I have tried to play around with the values but it doesn't seem to solve the issue. I searched a lot about this and even tried to follow this but it didn't work. I use the following block of code in the onCreate method of the Activity to implement it.

setContentView(R.layout.button_press);

        button = findViewById(R.id.my_button);
        button.setClickable(true);
        button.setOnClickListener(this);

        final Button button = (Button) findViewById(R.id.my_button);
        displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        loOPenArea = (RelativeLayout) findViewById(R.id.open_area_press);

        int leftMargin = new Random().nextInt(displaymetrics.widthPixels - 5*button.getWidth());
        int topMargin = new Random().nextInt(displaymetrics.heightPixels - 5*button.getHeight());

        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) button.getLayoutParams();
        p.setMargins(leftMargin, topMargin, 0, 0);

        button.setLayoutParams(p);

And here's the code for the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".ButtonPress"
    android:background="#03B0F5"
    >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/open_area_press">

    <TextView
        android:id="@+id/button_press"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:background="#FFFFFF"
        android:text="@string/button_press"
        android:textSize="50sp"
        android:textColor="#03B0F5"

        />

    <androidx.appcompat.widget.AppCompatButton
        android:id = "@+id/my_button"
        android:layout_width = "150dp"
        android:layout_below="@+id/button_press"
        android:height="150dp"
        android:layout_height = "wrap_content"
        android:background="@drawable/rounded_corners"
        android:text = "Press Here"
        android:textColor="#03B0F5"
        android:textSize="20sp"
        />



</RelativeLayout>

</LinearLayout>

Either sometimes the button doesn't show on the screen at all or it gets squeezed in some place(see bottom right corner):

enter image description here

Making a button appear on a random screen position seems like a trivial task, but I've been trying to solve it for days and look for solutions but none of the solutions seems to work perfectly.




Aucun commentaire:

Enregistrer un commentaire