Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 實現點擊 ImageView 挑選本地圖片並即時顯示

編輯:關於 Android 程式設計

需求很常見:點一下 ImageView,叫出系統相簿,選完照片後直接換上去。核心只是一個隱式 Intent 加上 onActivityResult。

執行結果:

模擬器裡只有三張圖,畫質就別太計較了。

布局檔

一個置中的方形 ImageView,先放張預設底圖:

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

    <ImageView
        android:id="@+id/image_choose"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:background="#CC0000"
        android:padding="5dp"
        android:src="@drawable/default_bg" />

</RelativeLayout>

MainActivity

package com.example.chooseimage;

import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;

public class MainActivity extends Activity implements OnClickListener {
    private ImageView image_choose;

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

        image_choose = (ImageView) findViewById(R.id.image_choose);
        image_choose.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image_choose:
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 0x1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x1 && resultCode == RESULT_OK) {
            if (data != null) {
                image_choose.setImageURI(data.getData());
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

兩個重點:

  • Intent.ACTION_PICK 搭配 setDataAndType(..., "image/*"),等於告訴系統「我要從相簿挑一張圖」,無需自己寫選擇器界面。
  • 回傳的 data.getData() 就是圖片的 content URI,直接交給 setImageURI 即可顯示。

若要處理大圖,記得後續加上 BitmapFactory.Options 的 inSampleSize 做降採樣,避免 OOM。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved