Skip to content

Instantly share code, notes, and snippets.

@xsota
Last active January 20, 2016 03:08
Show Gist options
  • Save xsota/93e69d8fd7b535fc3025 to your computer and use it in GitHub Desktop.
Save xsota/93e69d8fd7b535fc3025 to your computer and use it in GitHub Desktop.
package com.xsota.random;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.AbsoluteLayout;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//画面サイズを取得
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int WIDTH = metrics.widthPixels; //画面横サイズ
int HEIGHT = metrics.heightPixels; //画面縦サイズ
//絶対座標レイアウト
AbsoluteLayout absoluteLayout = new AbsoluteLayout(this);
setContentView(absoluteLayout);
//Buttonが生まれる
Button button = new Button(this);
button.setText("ほげ");
//ボタンのサイズを決める
int buttonSizeX = 150;
int buttonSizeY = 100;
//Buttonの位置をランダムに決める (横サイズ, 縦サイズ, 横座標, 縦座標)
int x = 0;
int y = 0;
Random random = new Random();
x = random.nextInt(WIDTH-buttonSizeX);//画面からはみ出ないようにButtonの大きさ分引いておく
y = random.nextInt(HEIGHT-buttonSizeY);
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(buttonSizeX,buttonSizeY, x, y);
//位置を指定してButtonを追加
absoluteLayout.addView(button, params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment