Android SDK の動かないコード(中級編) invalidate しても再描画されないエラー
以下のAndroidアプリのコードが意図した動作をしないのは,なぜですか。
(制限時間1分)
やりたい事:
- ボタン押下時に,ImageView上に画像を2枚連続で表示する。表示のタイミングをずらす事により,疑似的にスライドのように見せたい。(Gifアニメ的なものを作りたい)
package com.example; import com.example.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class CodeTestActivity extends Activity implements OnClickListener { Button button1; ImageView imageview1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // UI部品を取得 button1 = (Button)findViewById(R.id.button1); imageview1 = (ImageView)findViewById(R.id.imageview1); // ボタンにイベントをセット button1.setOnClickListener(this); } @Override public void onClick(View v) { // Android SDK(android.R)に内蔵されている画像を2つ表示する。 // 間隔を空けて表示することにより,アニメーションのように見せる。 // 1つ目の画像を表示する(検索ルーペのアイコン) imageview1.setImageResource(android.R.drawable.ic_menu_search); imageview1.invalidate(); // ビューを再描画し,UI上で画像変更を反映 // 2秒待って,タイムラグを生む try { Thread.sleep(2000); } catch (InterruptedException ignore) { } // 2つ目の画像を表示する(フロッピーの保存アイコン) imageview1.setImageResource(android.R.drawable.ic_menu_save); imageview1.invalidate(); // ビューを再描画し,UI上で画像変更を反映 } }
レイアウト用のmain.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <!-- ボタン --> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="画像を連続で表示" /> <!-- 画像 --> <ImageView android:id="@+id/imageview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/icon" /> </LinearLayout>続きを読む