ふわふわぷかぷか

最近はイラレとAeにはまってます。

画像をランダムに表示する。

こんなアプリを作ってます♪

f:id:fuwafuwapukapuka:20150809220009p:plain f:id:fuwafuwapukapuka:20150219214448j:plain f:id:fuwafuwapukapuka:20150223222756p:plain

 

イメージビューに画像をランダムに表示する方法。

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開発道場

炎のAndroid開発道場