画像をランダムに表示する。
こんなアプリを作ってます♪
イメージビューに画像をランダムに表示する方法。
strings.xmlに3つの画像を書いて、それをランダムに呼び出します。
画像はdrawableに入れました。
strings.xmlに画像の名前を並べました。
<array name="rgazou">
<item>@drawable/sonoiti</item>
<item>@drawable/sononi</item>
<item>@drawable/sonosan</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">
<ImageView
android:id="@+id/iv1"
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.rgazou); int i = (int) (Math.floor(Math.random() * (3); Drawable drawable = typedArray.getDrawable(i); iv1.setImageDrawable(drawable);
画像の数が3つなので()の中は3です。
Activity全体では、
public class HelloandroidActivity extends Activity implements OnClickListener {
Button button1; ImageView iv1;
/** 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);
iv1 = (ImageView)findViewById(R.id.iv1);
}
public void onClick(View v) {
if(v == button1){
TypedArray typedArray = getResources().obtainTypedArray(R.array.rgazou); int i = (int) (Math.floor(Math.random() * (3); Drawable drawable = typedArray.getDrawable(i); iv1.setImageDrawable(drawable);}
}}
これで、ボタンを押すと画像がランダムに表示されます。
- 作者: よちよちAndroidサンデープログラミングの会初心者教育委員会
- 出版社/メーカー: リックテレコム
- 発売日: 2012/08/31
- メディア: 単行本(ソフトカバー)
- 購入: 2人 クリック: 48回
- この商品を含むブログを見る