samedi 30 décembre 2017

Android java create buttons positioned randomly without exceed screen size

I'm trying to create an Activity that contains 10 buttons that are generated programmatically and are positioned in random places on the screen but without exceed the screen size.

I tried doing so but most of the buttons exceeded from the screen size (I couldn't see it).

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear);
    Random rnd = new Random();

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

    for(int x = 0;x<10;x++) {

        Button btn = new Button(this);

        int Xpoistion = rnd.nextInt(width - 100) + 100;
        int Yposition = rnd.nextInt(height - 100) + 100;

        btn.setX(Xpoistion);
        btn.setY(Yposition);

        btn.setText(x +")"+width + "," + height + " | " + Xpoistion + "," + Yposition);

        linearLayout.addView(btn);

    }

So i'm trying to create the "limits of the screen" from height and width but for some reason I can't figure it out.

I played with Xposition and Yposition a lot but nothing seems to work for me.

Thank for very much for your help.




Aucun commentaire:

Enregistrer un commentaire