Android開発のお勉強

メニュー

E-Mail



ネット上の画像を表示

 ネット上の画像を非同期で読み込んで表示します。
 
● 非同期処理
 AsyncTaskを継承したクラスを作成します。
 画像を読み込んで、画面に表示する非同期処理を実装します。
 


import java.io.InputStream;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;

public class ImageLoader extends AsyncTask<String, String, Bitmap> {

    private ImageView imageView;

    public ImageLoader(ImageView imageView) {
    
        // コンストラクタ
        // ImageViewを渡す
        this.imageView = imageView;
    }


    @Override
    protected Bitmap doInBackground(String... arg0) {

        // バックグラウンド処理

        Bitmap bitmap = null;
        try {

            // 指定したURLの画像を読み込む
            URL url = new URL(arg0[0]);
            InputStream input = url.openStream();
            bitmap = BitmapFactory.decodeStream(input);

        } catch(Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    protected void onPostExecute(Bitmap res) {
        //バックグラウンド処理が完了した時の処理

        // 読み込んだ画像をImageViewに設定
        this.imageView.setImageBitmap(res);
    }
}


● レイアウト
 画像を表示するImageViewを配置します。


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />

</RelativeLayout>




● Activity
 作成した非同期処理を実行します。
 

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;

public class ImageViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_view);

        // Activityに配置したImageViewを取得。
        ImageView imageView = (ImageView)findViewById(R.id.imageView1);
        // 作成した非同期処理のクラスを生成し、URLを指定して実行。
        ImageLoader imageLoader = new ImageLoader(imageView);
        imageLoader.execute("http://○○○");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_image_view, menu);
        return true;
    }
}






Copyright (C) Androidアプリ開発のお勉強. All Rights Reserved.