1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Android】assetsフォルダから画像を読み込みImageViewで表示する

Last updated at Posted at 2019-10-29

#事前準備
事前準備として,プロジェクトを立ち上げた時にassetsフォルダはできていないことが多いと思いますので,
スクリーンショット 2019-10-29 13.59.51.png
このようにmain以下にassetsフォルダを作成し,
スクリーンショット 2019-10-29 14.00.00.png
好きな画像をぶっこんでください.
そしたら準備完了です.

#さっそく本題
タイトルの通りのことを実装する場合には次のコードでいけます.

MainActivity.java

package com.example.****.***_imageview_test;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ImageView imageView = (ImageView)findViewById(R.id.image_view);
        Bitmap image = getBitmapFromAsset("youtube.png");
        imageView.setImageBitmap(image);
    }


    private Bitmap getBitmapFromAsset(String strName)
    {
        AssetManager assetManager = getAssets();
        InputStream istr = null;
        try {
            istr = assetManager.open(strName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(istr);
        return bitmap;
    }
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".MainActivity">


<ImageView
    android:id="@+id/image_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="@string/img_description1"
    android:scaleType="centerCrop" />

</android.support.constraint.ConstraintLayout>

以上でーす.シンプルですよねー!
android:id="@+id/image_view" や
android:contentDescription="@string/img_description1"
の設定は各自でお願い致します!🙇‍♂️

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?