Drawable で表示する方法もありますが、表示サイズの管理が面倒ですし、画像はいろいろな処理をテストする場合に目視で確実に結果を確認できるので、Bitmap(実際には Stream) で取り回して行くほうが良いと思います。
Nexus4 768x1280 : 画像 400x320
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private String image_url;
private ImageView imageView;
private URL url;
private InputStream inputStream;
private Bitmap bitmap = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image_url = "https://lightbox.sakura.ne.jp/demo/image/sample.jpg";
imageView = (ImageView) MainActivity.this.findViewById(R.id.imageView);
// ボタンをクリック
MainActivity.this.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new AsyncTask<String, Void, Bitmap>() {
// 非同期処理
@Override
protected Bitmap doInBackground(String... params) {
// Bitmap
bitmap = null;
try {
// インターネット上の画像を取得して、Bitmap に変換
url = new URL(params[0]);
inputStream = (InputStream) url.getContent();
bitmap = BitmapFactory.decodeStream(inputStream); // ここではオプションは指定していません
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
// UI スレッド処理
@Override
protected void onPostExecute(Bitmap bitmap) {
// Bitmap 取得に成功している場合は表示します
// ※ 引数のローカル変数を使用
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
Toast.makeText(MainActivity.this,"画像を表示しました",Toast.LENGTH_SHORT).show();
}
}
}.execute(image_url);
}
});
}
}
画面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@mipmap/ic_launcher"/>
</LinearLayout>
※ 要 android.permission.INTERNET
posted by
at 2018-03-17 19:19
|
Comment(0)
|
テンプレート
|

|