単語をランダムに表示する。
こんなアプリを作ってます♪
テキストビューに、ランダムで単語を表示する方法。
strings.xmlに3つの単語を書いて、それをランダムに呼び出します。
strings.xmlに単語を並べました。
<array name="rtango">
<item>りんご</item>
<item>みかん</item>
<item>ぶどう</item>
</array>
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/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ボタン" />
</LinearLayout>
単語をランダムに取得して、テキストビューに表示する部分は
TypedArray typedArray = getResources().obtainTypedArray(R.array.rtango);
int i = (int) (Math.floor(Math.random() * (3)) );
String str = typedArray.getString(i);
tv1.setText(str);
画像の数が3つなので()の中は3です。
Activity全体では、
public class HelloandroidActivity extends Activity implements OnClickListener {
Button button1; TextView tv1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
tv1 = (TextView)findViewById(R.id.tv1);
}
public void onClick(View v) {
if(v == button1){
TypedArray typedArray = getResources().obtainTypedArray(R.array.rtango);
int i = (int) (Math.floor(Math.random() * (3)) );
String str = typedArray.getString(i);
tv1.setText(str);}
}}
これで、ボタンを押すと単語がランダムに表示されます。
15歳からはじめるAndroidわくわくゲームプログラミング教室
- 作者: 掌田津耶乃,リブロワークス
- 出版社/メーカー: ラトルズ
- 発売日: 2011/01/07
- メディア: 単行本(ソフトカバー)
- 購入: 1人 クリック: 342回
- この商品を含むブログ (8件) を見る