数字をランダムに表示する。
ボタンを押したら、テキストビューに数字がランダムに表示されるようにします。
main.xmlは、数字を表示する用のテキストビューとボタンです。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#ffffff">
<TextView
android:id="@+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン" />
</LinearLayout>
Activityは、「import java.util.Random;」のインポートが必要です。
まず、ランダムの数字を取得する部分は
Random r = new Random();
int n = r.nextInt(10);
int n の n がランダムで取得された数字を表している気がします。
だからたぶん n でなくても変えても良さそう。
数字の始まりが1ではなく0からなので、上のように(10)だと、0~9のランダムになります。
1~10のランダムにする場合は、
Random r = new Random();
int n = r.nextInt(10)+1;
です。
これで出てきた数字は、そのままだとテキストビューには表示できないみたいなので、表示できる文字に変換して、テキストビューに表示します。
パソコン言語から人間言語に訳すってことなのかな?
@SuppressWarnings("unused")
String string = String.valueOf(n);
tv1.setText(String.valueOf(n));
これでテキストビューに表示できます。
Activity全部ではこうなりました。
public class MainActivity extends Activity implements OnClickListener{
TextView tv1;
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv1 = (TextView)findViewById(R.id.text1);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
if (v == button1) {
Random r = new Random();
int n = r.nextInt(10);
@SuppressWarnings("unused")
String string = String.valueOf(n);
tv1.setText(String.valueOf(n));
}}}
ボタンを押すたびに0~9の数字がランダムで表示されます。
数字の範囲を指定する場合、
例えば、5から9の数字をランダムで表示する場合は、
Random r = new Random();
int n = r.nextInt(10 - 5) + 5;
でできます。
スマートにプログラミング Android入門編 第3版 SDK4.x対応
- 作者: 堀切堤
- 出版社/メーカー: リックテレコム
- 発売日: 2013/05/11
- メディア: 単行本(ソフトカバー)
- この商品を含むブログ (5件) を見る