samedi 26 juin 2021

How to stop view from going out of screen for randomized positions?

I have a screen ButtonPress that shows a button on random positions, it is working for most of the iterations but in some, it is going out of the screen and the button is not visible. I tried to follow this example but that does not seem to help as the button is still invisible for some iterations in the ButtonPress activity. Here's how I am generating the random positions:

protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.button_press);

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

        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) button.getLayoutParams();
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        params.leftMargin = button.getWidth()
                + new Random().nextInt(metrics.widthPixels - 2*button.getWidth());
        params.topMargin = button.getHeight()
                + new Random().nextInt(metrics.heightPixels - 3*button.getHeight());
        button.setLayoutParams(params);


    }

And here's the layout file for the button:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#03B0F5"
    >

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


        <ImageView
            android:id="@+id/imageView5"
            android:layout_width="100dp"
            android:layout_height="100dp"
            app:srcCompat="@drawable/ic_button"
            tools:ignore="VectorDrawableCompat" />
</LinearLayout>

I removed all the padding and margins from this resource file but it's still not working.




Aucun commentaire:

Enregistrer un commentaire